Reputation: 13
I know this has been asked before but can't find a answer to my specific instance of this error.
Catchable fatal error: Object of class PDOStatement could not be converted to string
Here is my code:
try
{
// create connection and set error attributes
$conn = new PDO("mysql:host=" . HOST . "; dbname=" . DATABASE, USER, PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//define insert and query variables
$query = "SELECT * FROM cart WHERE user_id=? AND product_id=?;";
$insert = "INSERT INTO cart (user_id, product_id, qty, date)
VALUES ('$sessId', :i, :q, 'Now()');";
// execute a query to check if item all ready exist in cart
$r = $conn->prepare($query);
$r->execute(array(
session_id(),
$i
));
if ($r->rowCount() > 0) {
echo 'Item already exists in cart';
} else {
$q = $conn->prepare($insert);
$q->bindParam(':i', $i);
$q->bindParam(':q', $q);
$q->execute();
header('Location:../shopping_cart.php');
}
$r->closeCursor();
}
catch (PDOException $e)
{
echo $e->getMessage();
}
I cant find anything wrong with it, otherwise I just need to know what I need to do to get the values to convert, or should I look into another method.
Upvotes: 1
Views: 1683
Reputation: 1190
First you are testing if there is at least one record using
session_id()
If not then you are trying to insert with
$sessId
Assuming that they somehow have the same value...
I think you should insert with real prepared statement like:
$insert = "INSERT INTO cart (user_id, product_id, qty, date)
VALUES (:s, :i, :q, :n);";
...
...
...
$q = $conn->prepare($insert);
$q->bindParam(':s', $sessId);
$q->bindParam(':i', $i);
$q->bindParam(':q', $qty);
$q->bindParam(':n', Now());
$q->execute();
header('Location:../shopping_cart.php');
Upvotes: 1
Reputation: 2556
Change the name of variable $q
, you are changing type for nothing.
$q = $conn->prepare($insert);
$q->bindParam(':i', $i);
$q->bindParam(':q', $q); //binding a prepare statement itself?
Change to, and define the $qty
with initial value of $q
.
$q = $conn->prepare($insert);
$q->bindParam(':i', $i);
$q->bindParam(':q', $qty);
Upvotes: 3