PHP MySQL 查询数据库和 WHERE 子句

标签 php html mysql sql database

我正在学习 PHP 和 MySQL,并且在构建时遇到一两个问题。

我有一个 HTML 表单,用户可以输入他们的详细信息和狗的详细信息。然后该脚本检查数据库中的用户名和狗的名字。如果两者都存在于数据库中,则更改狗表上的 user_ID 以更改所有权。如果用户不存在,则用户详细信息将被输入数据库并更改所有权。

我确实让整个事情正常工作,但没有使用bindParam从表单中进行集合,并被告知这将是一个更好的选择。这就是乐趣的开始。我现在可以使用下面的脚本计算表中的行数,但是,我无法在 SELECT 查询中使用 WHERE 子句。我尝试放置“WHERE name_first = :name_first”,但失败并出现“参数未定义”错误。

我需要能够使用用户的名字和姓氏,以便能够从数据库中选择该用户 ID。

我还有一个关于使用准备好的语句的问题。如果我使用脚本顶部的语句从数据库中进行 SELECT 并且所有表单输入都绑定(bind)到 $STH,那么我如何运行不同的查询,例如如何使用以下命令将用户详细信息插入数据库相同的绑定(bind)?

有人可以看一下脚本并告诉我哪里出错了吗?

<?php

/***mysql username***/
$user = 'root';

/***mysql password***/
$pass = '';

if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {                   
    $DBH = new PDO('mysql:host=localhost;dbname=kennel_cert;', $user, $pass);
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    //Queries
    $sql1 = "SELECT user_ID FROM user_details";
    $sql2 = "SELECT dog_ID FROM dog_details";

    $STH = $DBH->prepare("SELECT * FROM user_details");  //Needs a WHERE clause to work
    //var_export($STH);

    //User details form
    $STH->bindParam(':name_first', $_POST['name_first']);
    $STH->bindParam(':name_last', $_POST['name_last']);
    $STH->bindParam(':email', $_POST['email']);
    $STH->bindParam(':telephone', $_POST['telephone']);
    $STH->bindParam(':name_number', $_POST['name_number']);
    $STH->bindParam(':street', $_POST['street']);
    $STH->bindParam(':city', $_POST['city']);
    $STH->bindParam(':county', $_POST['county']);
    $STH->bindParam(':postcode', $_POST['postcode']);

    //Dog details form
    $STH->bindParam(':dog_reg', $_POST['dog_reg']);
    $STH->bindParam(':name', $_POST['name']);
    $STH->bindParam(':microchip', $_POST['microchip']);
    $STH->bindParam(':gender', $_POST['gender']);
    $STH->bindParam(':day', $_POST['day']);
    $STH->bindParam(':month', $_POST['month']);
    $STH->bindParam(':year', $_POST['year']);

    $STH->execute();                                    //Execute the select script

    //Use this to count the users - However without the WHERE it is counting all users not the one submitted into the form
    if($STH->rowCount() > 0) {
        echo "Exists <br>"; }
    else {
        echo "Doesn't exist <br>"; }

    //var_export($userQuery);                           //Displays the contents of the query for testing

    //Find if user exists in database - Again another way of counting the total but not the one inputed into the form
    $userResult = $DBH->query($sql1);

    if ($userResult !== false) {
        $count = $userResult->rowCount();
        echo 'Number of users: '.$count. '<br>';

    foreach($userResult as $row) {
    echo $row['user_ID'].'<br>';
    }
    }

    //Find if dog exists in database - Again another way of counting the total but not the one inputed into the form
    $dogResult = $DBH->query($sql2);

    if ($dogResult !== false) {
        $count = $dogResult->rowCount();
        echo 'Number of dogs: '.$count. '<br>';

    foreach($dogResult as $row) {
    echo $row['dog_ID'].'<br>';
    }
    }



    } catch (PDOException $e) {
        echo $e->getMessage();
        }
        //echo "<p>Data submitted successfully</p>";
}       
//Disconnect from the server
$DBH = null;

?>
<小时/>

好的,我已将查询更改为如下所示:

$sql = "SELECT user_ID 
        FROM user_details 
        WHERE name_first = :name_first 
        AND name_last = :name_last";

$STH = $DBH->prepare($sql);

当我运行这个时,我收到此错误:

PDOStatement::__set_state(array( 'queryString' => 'SELECT user_ID FROM user_details        WHERE name_first = :name_first AND name_last = :name_last', ))

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

我完全迷失了,我在原地打转,找不到任何可以帮助我解决这个问题的东西。

我确实按照我所说的使用此设置运行了脚本,但是,我被告知要使用表单的bindParam,这会杀死脚本和我。

<?php

/***mysql username***/
$user = 'root';

/***mysql password***/
$pass = '';

if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {                   
    $DBH = new PDO('mysql:host=localhost;dbname=kennel_cert;', $user, $pass);
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    //Queries
    $userQuery = $DBH->query("SELECT user_ID FROM user_details WHERE name_first = '$first' AND name_last = '$last'"); //Checks if the user exists in the database
    $dogQuery = $DBH->query("SELECT dog_ID FROM dog_details WHERE dog_ID = '$dog_reg' AND name = '$name' AND gender = '$gender'"); 

    //User details form
    $first = $_POST['name_first'];
    $last = $_POST['name_last'];
    $email = $_POST['email'];
    $telephone = $_POST['telephone'];
    $name_number = $_POST['name_number'];
    $street = $_POST['street'];
    $city = $_POST['city'];
    $county = $_POST['county'];
    $postcode = $_POST['postcode'];

    //Dog details form
    $dog_reg = $_POST['dog_reg'];
    $name = $_POST['name'];
    $microchip = $_POST['microchip'];
    $gender = $_POST['gender'];
    $day = $_POST['day'];
    $month = $_POST['month'];
    $year = $_POST['year'];

    $u = "";                                                //Variable for counting users
    $d = "";                                            //Variable for counting dogs



    //var_export($userQuery);                           //Displays the contents of the query for testing

    //Find if user exists in database
    foreach($userQuery as $row1) {                      //Count the number of users in the database
    $u++;
    }

    //Find if dog exists in database
    foreach($dogQuery as $row2) {                       //Count the number of dogs in the database
    $d++;
    }

    //The echos are for testing purposes
    echo "Dog ID is: ".$row2['dog_ID']."<br>";          //Finds the ID of the dog and displays it
    echo "User ID is: ".$row1['user_ID']."<br>";        //Finds the ID of the user and displays it
    $newUserID = $row1['user_ID'];                      //Store the ID for future use
    $newDogID = $row2['dog_ID'];                        //Store the ID for future use

    //Perform if both user and dog exist
    if ($u > 0 && $d > 0) {                             //If both the user and the dog exist in the database change the owner of the dog
        echo "Both Match";                              //Confirm both exist
        $q = $DBH->prepare("UPDATE dog_details SET user_ID = '$newUserID' WHERE dog_ID = '$newDogID'");  //update the table to change ownership
        $q->execute();                                  //Execute the change
        }

    // Perform if only dog exists
    elseif ($u == 0 && $d > 0) {                        //If the user does not exist but the dog does.
        echo "Dog matches but user does not exist";     //Confirm what exists
        //Insert user details into user_details table and set the foreign user_ID key in the dog_details table 
        $q1 = $DBH->prepare("INSERT INTO user_details (name_first,name_last,email,telephone,name_number,street,city,county,postcode) VALUES ('$first','$last','$email','$telephone','$name_number','$street','$city','$county','$postcode')");
        $q1->execute();
        echo "<br>Insert complete<br>";*/


        }
    elseif ($u > 0 && $d == 0) {
        echo "The dog does not exist - this is a problem";  
        //Form needs returning with values and asks user to check details
        }
    elseif ($u == 0 && $d == 0) {
        echo "Both don't match";
        }

    } catch (PDOException $e) {
        echo $e->getMessage();
        }
        //echo "<p>Data submitted successfully</p>";
}       
//Disconnect from the server
$DBH = null;

?>

最佳答案

检查manual绑定(bind)参数之前需要在sql中放入占位符:

$query = "SELECT * FROM user_details 
          WHERE name_first = :name_first 
            AND name_last = :name_last 
            AND email = :email
            etc...";

$STH = $DBH->prepare($query);

关于PHP MySQL 查询数据库和 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23585236/

相关文章:

php - UTF-8贯穿始终

html - @media 上的文本输入没有改变

php - 网页样式更改后不起作用

php - MySQL LEFT OUTER JOIN 未给出正确的结果

php - 我需要从两个表中拉入一个循环并匹配数据

javascript - 将元素内的文本模糊匹配到时间字符串

MySQL:为什么数据库表上的基本 MySQLdump 失败并显示 "Permission denied"

mysql - 用符号导入mysql

php - 从数据库 Likr facebook **查找 friend ** 页面搜索过滤,PHP

php - 如何优化此查询以快速加载 friend