if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){
$productID = $_REQUEST['id'];
// get product details
$query = $db->query("SELECT * FROM products WHERE id = ".$productID);
$row = $query->fetch_assoc();
$itemData = array(
'id' => $row['id'],
'name' => $row['name'],
'price' => $row['price'],
'qty' => 1
);
$insertItem = $cart->insert($itemData);
$redirectLoc = $insertItem?'viewCart.php':'index.php';
header("Location: ".$redirectLoc);
}
I'm trying to convert this code to PDO stmt. Please help me with this, I'm new here.
You need to develop and pdo connection with whichever database you have. Check the connection check and connect with it.
Make sure that you have install PDO library, check it your php info.
try
{
$conn =new PDO("sqlsrv:Server=$this->hostName;Database=$this->dbName", "$this->userName", "$this->password");
$productID = $_REQUEST['id'];
$sql = "SELECT * FROM products WHERE id=?";
$stmt->bindParam(1, $productID);
$stmt = $conn->prepare($sql);
$this->result = $stmt->execute();
if (!$this->result)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$itemData = array(
'id' => $row['id'],
'name' => $row['name'],
'price' => $row['price'],
'qty' => 1
);
}
}
$insertItem = $cart->insert($itemData);
$redirectLoc = $insertItem?'viewCart.php':'index.php';
header("Location: ".$redirectLoc);
}
catch(Exception e)
{
echo $e->getMessage();
exit();
}
Related
This is a code to update a table with foreach loop. But it update the last value three times which is POST[s3_name]
<?php
$names = [$_POST['s1_name'], $_POST['s2_name'], $_POST['s3_name']];
$query = "update students SET Name=:Name WHERE ProjectID='$id'";
foreach ($names as $name) {
try
{
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
You could get the id from somewhere and loop that as well. Something like this
$names = [
['id' => 1, 'name' => 'name1'],
['id' => 2, 'name' => 'name2'],
['id' => 3, 'name' => 'name3']
];
foreach ($names as $name) {
try {
$query = "update students SET Name=:Name WHERE ProjectID=:Id";
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name['name']);
$stmt->bindParam(':Id', $name['id']);
$result = $stmt->execute();
$msg = "Record updated";
} catch(PDOException $ex) {
$msg = $ex -> getMessage();
}
}
I have this function which I use to get a value from a query. I might be doing something wrong with the execution, or the syntax. When I try to run the query with the data in it, it's fine, but this one returns 0 items.
public function get_modified_event ($type, $id, $employee_id)
{
global $dbh;
$sql =<<<SQL
SELECT outlook_id
FROM dba.events
WHERE spine_item_type = :type
AND spine_id = :id
AND employee_id = :employee_id
SQL;
$stmt = $dbh->prepare( $sql );
$stmt->execute( array(
'id' => $id,
'type' => $type,
'employee_id' => $employee_id,
) );
$rows = $stmt->fetchAll( \PDO::FETCH_ASSOC );
return $rows['outlook_id'];
}
You could try reworking a portion of the code so that it uses this kind of a format:
$stmt = $dbh->prepare( $sql );
if ($stmt->execute( /* your array goes here */ )) {
$rows = $stmt->fetchAll( PDO::FETCH_ASSOC );
if ($rows !== FALSE){
print_r($rows);
}
else
if ( $stmt->rowCount() === 0) {
echo "The info provided is unknown to the database";
}
}
Hopefully you'll get some meaningful results.
I have some sql statements that accepts a number and if that number is equal to the value of a column in a database, it should return all rows in the database that has the same value. Unfortunately the rows only return blog_post_id that has a value 0.
This is my codes below:
<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id']
: '';
$pdo=new PDO("mysql:dbname=db;host=localhost","username","password",
$options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id =
'$blog_post_id'");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
if ($json)
echo $json;
else
echo json_last_error_msg();
?>
You are actually missing the point of using the function prepare() and you need to check if the query does actually return any results..
<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id'] : '';
$pdo = new PDO("mysql:dbname=db;host=localhost", "username", "password", $options);
$statement = $pdo->prepare("SELECT * FROM comment WHERE blog_post_id = ?");
$statement->execute([$blog_post_id]);
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = array();
if (count($results) > 0) {
foreach ($results as $row) {
$json[] = array(
'id' => $row['blog_post_id'],
'Field' => $row['Column'],
'AnotherField' => $row['AnotherColumn'],
'AnotherField1' => $row['AnotherColumn1'],
'ETC' => $row['AnotherColumnName']
);
}
echo json_encode($json);
} else {
echo "no data found";
}
?>
You should do variable binding like so:
$pdo=new PDO("mysql:dbname=db;host=localhost","username","password", $options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id = :blog_post_id");
$statement->execute(['blog_post_id' => $blog_post_id]);
This will also prevent 1st level SQL-Injection as described here: Are PDO prepared statements sufficient to prevent SQL injection?
I'm using php to connect to mysql database and am using the following function to retrieve multiple rows from database and then add them to an array and send them back. I'm getting internal server error or 500x error messages. I'm not sure what is wrong with this code. I've tried to figure it out but can't get it.
public function getUnreadMessages($uname){
$stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?");
$status = 'unread';
$stmt->bind_param("ss", $uname, $status);
if ($stmt->execute()) {
$stmt->bind_result($col1, $col2, $col3);
$stmt->store_result();
$resp = array();
while($stmt->fetch()){
$row = array();
array_push($row, $col1, $col2, $col3);
array_push($resp, $row);
}
$msg = array('msgid' => $msgid,'title' => $title,'fromuname' => $fromuname);
$stmt->close();
return $msg;
} else {
$stmt->close();
return NULL;
}
}
how should I go about doing this? The function that handles the returned results are as follows
$app->get('/inbox', 'authenticate', function() use ($app){
ob_start("ob_gzhandler");
global $global_user_name;
$db = new DbHandler();
$resp = $db->getUnreadMessages($global_user_name);
$msgs = array();
$msgs['status'] = 'success';
$msgs['version'] = 0.1;
array_push($msgs, $resp);
$app->response()->header('Content-Type', 'application/json');
echo json_encode($msgs);
exit;
});
The PDO method automating this is $stmt->fetchAll() :D
public function getUnreadMessages($uname)
{
$stmt = $this->conn->prepare("SELECT msgid,title,fromuname FROM messages WHERE touname = ? and status = ?");
$stmt->execute([$uname, 'unread']))
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
Return false if nothing has been found or something like :
$msg = [
[
'msgid' => 2746,
'title' => 'Random title',
'fromuname' => 'SomeGuy'
],
[
'msgid' => 754,
'title' => 'Some title',
'fromuname' => 'Random Name'
],
[
'msgid' => 27686,
'title' => 'Unreadable title',
'fromuname' => 'Training dummies'
],
];
I've solved my question. It was that I was creating an array within a loop. This seems to be disallowed. Here's the code that did work in the end
public function getUnreadMessages($uname){
$stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?");
$status = 'unread';
$stmt->bind_param("ss", $uname, $status);
$result = $stmt->execute();
$stmt->bind_result($col1, $col2, $col3);
$stmt->store_result();
$outer = array();
$inner = array();
while($stmt->fetch()){
array_push($inner, $col1, $col2, $col3);
}
array_push($outer, $inner);
return $outer;
$stmt->close();
}
I am using PHP PDO for work with database SQLITE3. Can somebody show me how to put this commands in one transaction ?
$db = new PDO('sqlite:/var/db/fan_coil.db');
$sql = 'DELETE FROM fan_coil_plan WHERE fan_coil_id = :fan_coil_id;';
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':fan_coil_id' => $fan_coil_id));
$sql = ' DELETE FROM fan_coil_working_mode WHERE fan_coil_id = :fan_coil_id;';
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':fan_coil_id' => $fan_coil_id));
//****************** inserting working mode *************************************************************************************************
$i = 0;
$sql = 'INSERT INTO fan_coil_working_mode
(fan_coil_id,working_mode, temperature_set_point, max_positive_temperature,min_positive_temperature,mode_type,max_fan_speed)
VALUES(:fan_coil_id,:working_mode,:temperature_set_point,:max_positive_temperature,:min_positive_temperature,:mode_type,:max_fan_speed)';
$sth = $db->prepare($sql);
foreach ($modes as $key => $value) {
//file_put_contents('error.txt',$value['temperature_set_point'], FILE_APPEND );
$working_mode = '0'; //treba da se izbaci ova kolona iz tabele
$temperature_set_point = $value['temperature_set_point'];
$max_positive_variation = $value['max_positive_variation'];
$min_positive_variation = $value['min_positive_variation'];
$max_fan_speed = $value['max_fan_speed'];
$mode_type = ++$i;
$sth->execute(array(':fan_coil_id' => $fan_coil_id, ':working_mode' => $working_mode, ':temperature_set_point' => $temperature_set_point, ':max_positive_temperature' => $max_positive_temperature, ':min_positive_temperature' => $min_positive_temperature, ':mode_type' => $mode_type, ':max_fan_speed' => $max_fan_speeed));
}
$db = new PDO('sqlite:/var/db/fan_coil.db');
$db->beginTransaction();
try {
// your code
$db->commit();
}catch(PDOException $e) {
$db->rollBack();
throw $e;
}