camnesia camnesia - 1 year ago 67
SQL Question

How to store SQL query result in a variable using PHP?

I want to store the first query result in a variable and use the first query result as a value in the second query.

Currently the second query works on its own. I am just having difficulties getting the first one to work.

$var = array();$idorigin = $conn->prepare("SELECT id_stop FROM stops WHERE
stopname = '$value1'");
$var[] = $idorigin['id_Stop'];
echo $var;

$stmt = $conn->prepare("SELECT id_stop, scheduletime FROM schedule
WHERE scheduletime >= '$time' AND id_stop = '8'
LIMIT 6;");

echo $stmt;

Answer Source

You could use something like this for your first statement :

$req = $conn->prepare("SELECT id_stop FROM stops WHERE stopname = :value");
$req->execute(array('value' => $value1));
$result = $req->fetchAll();
  1. First you prepare your query
  2. Execute it with the corresponding parameters
  3. Fetch all records from the DB and store the result in any variable (here $result)
  4. Close connection with server, which allows to run other queries after
  5. Display the content of your variable with var_dump

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download