简体   繁体   English

PHP PDO Crud建议

[英]PHP PDO Crud advice

I have just started to learn PDO and have managed to do simple CRUD operations on one single table. 我刚刚开始学习PDO,并且已经设法在一个表上执行简单的CRUD操作。

I am just doing a SELECT * from the table. 我只是从表中执行SELECT *。 But this table has a foreign key to another table, and I would rather show the value on that column instead of a ID. 但是此表具有另一个表的外键,我宁愿在该列上显示值而不是ID。

So my table structure is the following. 所以我的表结构如下。 I have a joke table with id and joketext and a foreign key authorId. 我有一个具有ID和joketext的笑话表以及一个外键authorId。 The author table has authorId and name for the author. author表具有authorId和作者名称。

Instead of doing SELECT * on the joke table, I would rather create a view with the following code: 与其在笑话表上执行SELECT *,不如使用以下代码创建视图:

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

But for the CRUD operations I would like to show the author.name in a dropdown instead, so the users don't erroneously put in wrong values. 但是对于CRUD操作,我想改为在下拉列表中显示author.name,这样用户就不会错误地输入错误的值。

This is how index.php looks like: 这就是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>

and my edit file looks like this: 我的编辑文件如下所示:

<?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>

Can someone show me a hint on at least the edit operations how the php code would like? 有人可以告诉我至少有关php代码的编辑操作提示吗?

thanks 谢谢

If you wish to provide a select element of available authors for the user to choose from on the edit page, rather than have them enter an ID number for an author, then you can select all the authors from the database and loop through them, building the options of your select element. 如果您希望在编辑页面上提供可供选择的作者供用户选择的元素,而不是让他们输入作者的ID号,则可以从数据库中选择所有作者并循环遍历,从而构建选择元素的选项。 A select element can show the user the name of the author, but pass the ID of the author back to the server. select元素可以向用户显示作者的姓名,但可以将作者的ID传递回服务器。 You can also pre-select an author to show the user the currently associated author by default and they only have to change it if it's wrong. 您还可以预选择一个作者,以在默认情况下向用户显示当前关联的作者,并且只有在错误的情况下,他们才需要对其进行更改。

So first, select all the authors from the database: 因此,首先,从数据库中选择所有作者:

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

Then use that data to build a select element: 然后使用该数据构建一个select元素:

<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>

The output might look something like this: 输出可能看起来像这样:

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

Whatever option the user selects, they'll see on the page what is between the <option></option> tags, but the form will pass the value of the value property to the server as the authorid parameter. 无论用户选择什么选项,他们都会在页面上看到<option></option>标记之间的内容,但是表单会将value属性的value作为authorid参数传递给服务器。

The code that generates the select element replaces the <input type="text" name="authorid" value="<?php echo $authorid;?>"> and remains within the <td></td> tags. 生成select元素的代码替换<input type="text" name="authorid" value="<?php echo $authorid;?>">并保留在<td></td>标记内。

Hope I managed to address your actual need, let me know if I missed the intent of your question. 希望我能够解决您的实际需求,如果我错过了您提出问题的意图,请告诉我。

Note: my code isn't tested, so some adjustment may be required. 注意:我的代码未经测试,因此可能需要进行一些调整。


EDIT #1: Fixed incorrect variable names. 编辑#1:修正了不正确的变量名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM