I'm using this code for my school project in which my program should be able to reply automatically to queries which was sent to it using an open-source program.
I have succeeded on creating a simple auto-reply with it with the help of someone who is knowledgeable with it. However I'm struggling on getting values through PHP-MySQL with string variables.
$reqproduct = $db->query("SELECT Crop FROM crops WHERE Crop = '$product'");
$reqprice = $db->query("SELECT Price FROM crops WHERE Crop = '$product'");
And yes of course, I've failed horribly.
Then I tried to learn PHP:PDO but I still get stuck on how to use its commands even with the help of its documentation.
Here is an excerpt of what I'm trying to do:
<?php
try{
//test database connection
$db = new PDO('mysql:host=localhost;dbname=gammu;','root');
echo "Connected<p>";}
catch (Exception $e){echo "Unable to connect: " . $e->getMessage() ."<p>";}
//get data from database through decoded message
$product = 'Okra'; //sample decoded message
$sth = $db->prepare('SELECT Crop FROM crops WHERE Crop = :product');
$sth->execute(array(':product' => "{$product}"));
$result = $sth->fetchAll();
foreach ($result as $row) { $reqproduct = $row; break;}
$sth = $db->prepare('SELECT Price FROM crops WHERE Crop = :product');
$sth->execute(array(':product' => "{$product}"));
$result = $sth->fetchAll();
foreach ($result as $row) { $reqprice = $row; break;}
//to be sent to the sender
$message = "The price of $reqproduct is $reqprice/kilo." ;
echo $message;
$db = null;
?>
I would like to get the value of what's inside the $message, any help would be really appreciated.
Also, crops.sql contains 3 columns. Namely the 'ID', 'Crop', and 'Price'.
$row, and$result, usevar_dump($result);andvar_dump($row);The first is a 2D array containing the second. So you need to retrieve your valueCropby its array index.$reqprice = $row['Crop'];{}blocks in the control structures likeforeach, and don't use"{$product}"when you just need the variable$product.