简体   繁体   中英

PHP/SQL Query - Inserting a Variable Inside a String Variable

Trying to insert a variable inside a string variable that will be used as a query.

    $staffID = $_GET["staffID"];

    $conn = mysqli_connect("localhost", "twa095", "twa095de", "factory095");

    if ( !$conn ) 
    {
    die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT staffName, orderID, orderDate, shippingDate
    FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID
    WHERE staffID = $staffID // Problem is over here. 
    GROUP BY orderDate"

    $results = mysqli_query($conn, $sql)
    or die ('Problem with query' . mysqli_error($conn));

    ?>

Getting this as error:

Problem with queryColumn 'staffID' in where clause is ambiguous

Also, is there a way I can have it check whether the given "staffID" (first line) is inside the database and if it isn't to terminate the script and display an error message before everything below it executes?

Actually staffID is present in both joined tables (purchase and staff). Mysql is confused either staffID is from purchase table or staff table. To resolve your problem add tablename. to the staffID in where clause of your query as:

$sql = "SELECT staffName, orderID, orderDate, shippingDate
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID
WHERE staff.staffID = '{$staffID}' // Problem is over here. 
GROUP BY orderDate"

Also as a best practice add {} around the variable inside another string and single quotes in case variable is empty it will work fine.

Secondly, For checking if staff id is already in table and returning error you have to use mysqli_num_rows() inside the if clause and print error message to user as:

$sql = "SELECT staffName, orderID, orderDate, shippingDate
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID
WHERE staff.staffID = $staffID // Problem is over here. 
GROUP BY orderDate"

$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));

if(mysqli_num_rows($conn,$result)>0){
    echo "Error Message";
    exit;
}

You probably need single quotes around your variable name in your query:

WHERE staff.staffID = $staffID // Problem is over here. Should change to:

WHERE staff.staffID = '$staffID'

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