簡體   English   中英

PHP MySQL查詢數據庫和WHERE子句

[英]PHP MySQL query database and WHERE clause

我正在學習PHP和MySQL,並且在構建時遇到一兩個問題。

我有一個HTML表單,用戶可以輸入他們的詳細信息和狗的詳細信息。 然后,腳本檢查數據庫中的用戶名和狗名。 如果兩者都存在於數據庫中,則更改狗表上的user_ID以更改所有權。 如果用戶不存在,則將用戶詳細信息輸入數據庫,並更改所有權。

我確實完成了所有工作,但是沒有從表單中使用bindParam進行收集,並被告知這將是一個更好的選擇。 這就是樂趣的開始。 現在,我可以使用以下腳本對表中的行進行計數,但是,我無法在SELECT查詢中使用WHERE子句。 我曾嘗試放置“ WHERE name_first =:name_first”,但這失敗,並出現“ Parameter not defined”錯誤。

我需要能夠同時使用用戶的名字和姓氏,以便能夠從數據庫中選擇該用戶ID。

關於准備好的陳述的使用,我還有另一個問題。 如果我使用腳本頂部的語句從數據庫中進行SELECT,並且所有表單輸入都綁定到$ STH,那么我該如何運行另一個查詢,例如,如何使用用戶名將用戶詳細信息插入數據庫中?相同的約束?

有人可以看一下腳本,然后告訴我我要去哪里了嗎?

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

?>

查閱需要在綁定參數之前將占位符放在sql中的手冊

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM