I took my old mysql script and attempted to convert it to a more secure PDO format. In my old script I ran a SELECT field FROM table statement then put it into a variable
$Product = $row[‘product’]; and run an IF and ELSE statement. If the users product = sony I wanted to echo ” you may be interested in these as well” Here is my example code below
<?php
$connect = mysql_connect("host","username","password");
mysql_select_db("dbname");
$username = $_SESSION['username'];
$q = "SELECT product FROM users WHERE username = ('$username')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Product = $row['product'];
if($Product == "sony")
{
echo "You may be interested in these as well";
}
?>
Now with the PDO-Statement, it seems you can not run the same sort of statement as before as easiliy. I tried assigning a variable to the row product that my query is selecting from but I get the error:
Cannot use object of type PDOStatement as array
Here is my code
<?php
session_start();
$db = new PDO('mysql:host=host;dbname=dbname;charset=UTF-8', 'username', 'password');
$username = $_SESSION['username'];
$getProduct = $db->query("SELECT product FROM users WHERE username = '$username'");
$getProduct->execute();
$Product = $getProduct['product'];
if($Product == "sony")
{
echo "You may be interested in these as well";
}
?>
How can I pass the field “product” from the table I am selecting from to a variable with PDO and IF the product =”sony” echo “message”; ?
I also tried replacing the statements with this too with no success.
<?php
$query = $db->query("SELECT product FROM users WHERE username = '$username'");
$query->execute();
$Product = $query ->fetchAll(PDO::FETCH_ASSOC);
$Product = $getProduct['product'];
if($Product == "sony")
{
echo "You may be interested in these as well";
}
?>
The manual is not very friendly in regards to converting old statements to newer and secure ones, so I appreciate any direction on this, thank you.
use
to get 1 row and
to get all rows
You are expecting one row so use the first one.