简体   繁体   中英

write sql query in php

the following sql query works perfectly in phpAdmin.

SELECT response_text FROM statement_responses WHERE response_code = "s1_r1"

it doesn't work without the speech marks around response_code value.

I'm attempting to use the value of response_text in php.

for ($x = 1; $x <= 9; $x++) {   
    $user_response = ${"statement_" . $x . "_response"};
    $sql = "SELECT response_text FROM statement_responses WHERE response_code = \"$user_response\"";
    $result = mysqli_query($sql);
    $value = mysqli_fetch_object($result);
    echo $user_response . "<br>";
    echo $sql . "<br>";
    echo $result . "<br>";
    echo $value . "<br>";
}

The echoes allow me to see what each of the variables contains.

I get the following:

s1_r3 (the value of $user_response)

SELECT response_text FROM statement_responses WHERE response_code = "s1_r3" (the value of $sql - which is identical to the phpAdmin query that works.)

There are no values echoed for $result or $value .

What am I doing wrong, please? Why am I not getting the values from the database into my php code?

The first parameter for the mysqli_query should be the database connection created with mysqli_connect . Similarily, the first parameter for the mysqli_fetch_object , should be the result set identifier returned by mysqli_query .

It is a good practice to check the return values from the functions you call.

firstly, thank you for all of the responses. The following code works - ie it returns the value contained in 'response_text' column with the selected row identified by 'response_code' for use as the value of $response_text.

for ($x = 1; $x <= 9; $x++) {

$user_response_pre = ${"statement_" . $x . "_response"};

$user_response = "\"'" . $user_response_pre . "'\"";

$sql = "SELECT response_text FROM statement_responses WHERE response_code = $user_response";

$result = mysqli_query($conn, $sql);

$row = mysqli_fetch_array($result);

$response_text = $row[0];

${"statement_" . $x . "_complete"} .= $response_text;

}

you can write like this

for ($x = 1; $x <= 9; $x++) {   
    $user_response = ${"statement_" . $x . "_response"};
    $sql = 'SELECT response_text FROM statement_responses WHERE response_code = "'.$user_response.'"';
    $result = mysqli_query($sql);
    $value = mysqli_fetch_object($result);
    echo $user_response . "<br>";
    echo $sql . "<br>";
    echo $result . "<br>";
    echo $value . "<br>";
}

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