简体   繁体   中英

PHP PDO Crud advice

I have just started to learn PDO and have managed to do simple CRUD operations on one single table.

I am just doing a SELECT * from the table. But this table has a foreign key to another table, and I would rather show the value on that column instead of a ID.

So my table structure is the following. I have a joke table with id and joketext and a foreign key authorId. The author table has authorId and name for the author.

Instead of doing SELECT * on the joke table, I would rather create a view with the following code:

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.

This is how index.php looks like:

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

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. A select element can show the user the name of the author, but pass the ID of the author back to the server. 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 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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