PHP PDO Crud 建议

标签 php mysql pdo

我刚刚开始学习 PDO,并已成功在一张表上执行简单的 CRUD 操作。

我只是从表中执行 SELECT * 操作。但是这个表有另一个表的外键,我宁愿显示该列上的值而不是 ID。

所以我的表结构如下。我有一个笑话表,其中包含 id 和笑话文本以及外键authorId。作者表包含作者的authorId 和姓名。

我宁愿使用以下代码创建一个 View ,而不是在笑话表上执行 SELECT *:

SELECT
joke.joketext,
author.name
FROM
author
INNER JOIN joke
 ON author.id = joke.authorid

但是对于 CRUD 操作,我想在下拉列表中显示作者姓名,这样用户就不会错误地输入错误的值。

这就是index.php的样子:

<?php
//including the database connection file
include_once("config.php");

//fetching data in descending order (lastest entry first)
$result = $dbConn->query("SELECT * FROM joke ORDER BY id DESC");
?>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <a href="add.html">Add New Data</a><br/><br/>

    <table width='80%' border=0>

    <tr bgcolor='#CCCCCC'>
        <td>Joke</td>
        <td>AuthorId</td>
        <td>Update</td>
    </tr>
    <?php     
    while($row = $result->fetch(PDO::FETCH_ASSOC)) {         
        echo "<tr>";
        echo "<td>".$row['joketext']."</td>";
        echo "<td>".$row['authorid']."</td>";
        echo "<td><a href=\"edit.php?id=$row[id]\">Edit</a> | <a href=\"delete.php?id=$row[id]\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";        
    }
    ?>
    </table>

我的编辑文件如下所示:

<?php
// including the database connection file
include_once("config.php");

if(isset($_POST['update']))
{    
    $id = $_POST['id'];

    $name=$_POST['joketext'];
    $authorid=$_POST['authorid']; 

    // checking empty fields
    if(empty($joketext) || empty($authorid)) {    

        if(empty($joketext)) {
            echo "<font color='red'>Name field is empty.</font><br/>";
        }

        if(empty($authorid)) {
            echo "<font color='red'>Author field is empty.</font><br/>";
        }


    } else {    
        //updating the table
        $sql = "UPDATE joke SET joke=:joketext, authorid=:authorid WHERE id=:id";
        $query = $dbConn->prepare($sql);

        $query->bindparam(':id', $id);
        $query->bindparam(':joketext', $joketext);
        $query->bindparam(':authorid', $authorid);
        $query->execute();

        // Alternative to above bindparam and execute
        // $query->execute(array(':id' => $id, ':name' => $name, ':email' => $email, ':age' => $age));

        //redirectig to the display page. In our case, it is index.php
        header("Location: index.php");
    }
}
?>
<?php
//getting id from url
$id = $_GET['id'];

//selecting data associated with this particular id
$sql = "SELECT * FROM joke WHERE id=:id";
$query = $dbConn->prepare($sql);
$query->execute(array(':id' => $id));

while($row = $query->fetch(PDO::FETCH_ASSOC))
{
    $joketext = $row['joketext'];
    $authorid = $row['authorid'];
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <a href="index.php">Home</a>
    <br/><br/>

    <form name="form1" method="post" action="edit.php">
        <table border="0">
            <tr> 
                <td>Joke</td>
                <td><input type="text" name="joketext" value="<?php echo $joketext;?>"></td>
            </tr>
            <tr> 
                <td>Author</td>
                <td><input type="text" name="authorid" value="<?php echo $authorid;?>"></td>
            </tr>

            <tr>
                <td><input type="hidden" name="id" value=<?php echo $_GET['id'];?></td>
                <td><input type="submit" name="update" value="Update"></td>
            </tr>
        </table>
    </form>

有人可以告诉我至少有关 php 代码的编辑操作的提示吗?

谢谢

最佳答案

如果您希望在编辑页面上提供可用作者的选择元素供用户选择,而不是让他们输入作者的 ID 号,那么您可以从数据库中选择所有作者并循环遍历他们,构建您选择的元素的选项。 select 元素可以向用户显示作者的姓名,但将作者的 ID 传递回服务器。您还可以预先选择作者,默认情况下向用户显示当前关联的作者,只有在错误时他们才需要更改。

首先,从数据库中选择所有作者:

$authorSql = 'SELECT * FROM author';
$authorQuery = $dbConn->prepare($authorSql);
$authorQuery->execute();

然后使用该数据构建选择元素:

<select name="authorid">
<?php
    while($author = $authorQuery->fetch(PDO::FETCH_ASSOC)) {
        if ($author['id'] == $authorid) {
            //The author is currently associated to the joke, select it by default
            echo "<option value=\"{$author['id']}\" selected>{$author['name']}</option>";
        } else {
            //The author is not currently associated to the joke
            echo "<option value=\"{$author['id']}\">{$author['name']}</option>";
        }
    }
?>
</select>

输出可能如下所示:

<select name="authorid">
    <option value="1">George Carlin</option>
    <option value="2" selected>Richard Pryor</option>
    <option value="3">Don Rickles</option>
</select>

无论用户选择什么选项,他们都会在页面上看到 <option></option> 之间的内容。标签,但表单将传递 value 的值服务器的属性为 authorid参数。

生成 select 元素的代码替换 <input type="text" name="authorid" value="<?php echo $authorid;?>">并保持在<td></td>内标签。

希望我能够满足您的实际需求,如果我错过了您问题的意图,请告诉我。

注意:我的代码未经测试,因此可能需要进行一些调整。

<小时/>

编辑#1:修复了不正确的变量名称。

关于PHP PDO Crud 建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330539/

相关文章:

php - 如果条件和按条件分组不起作用

PHP 绑定(bind)变量、无效参数号错误或 PDO 更新语句

php - MySQL 根据现有值插入选择

php - PDO 错误 - PDOException',消息为 'SQLSTATE[HY000]: General error'

php - 更新数据在 Php 和 MySql 中不起作用

javascript - 如何从 JSON 生成 Javascript 对象

mysql - 如何根据此数据找出 1 周间隔的顶级股票(失败者)

php - 如何最好地实现数据库驱动的动态 url/ Controller 名称?

php - 添加 1 行计数器并使用 php 中的 fputcsv 首先更改最后一个 header

php - 带有随机图像的 3x3 表格 - PHP