mysqli to PDO Translation - php

The following code is for me at least straight forward. I want to to achieve the same thing using PDO. However, try as I may I simply can't get my head around the concept. Could someone please explain?
//Connect to a database.
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die("Couldn't connect to database.");
//Delete from the multiple tables.
$sql = "DELETE FROM table1, table2, tables3, tables4 WHERE id='75'";
$result = mysqli_query($link , $sql);

Here you go, using prepared statements just for showing as id = 75 is no user input - but that's the better way and using a transaction - in case you want to delete/update/insert more data at a time this is way faster.
$id = 75;
try {
$pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME , DB_USER, DB_PASS);
$pdo->beginTransaction();
$st = $pdo->prepare('DELETE FROM table1 WHERE id = :id');
$st->execute(array(':id', $id));
$st = $pdo->prepare('DELETE FROM table2 WHERE id = :id');
$st->execute(array(':id', $id));
$st = $pdo->prepare('DELETE FROM table3 WHERE id = :id');
$st->execute(array(':id', $id));
$st = $pdo->prepare('DELETE FROM table4 WHERE id = :id');
$st->execute(array(':id', $id));
$pdo->commit();
}
catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
SIDENOTE:
To write less, do it like this:
$array = array('table1','table2','table3','table4');
foreach ($array as $table) {
$st = $pdo->prepare('DELETE FROM '.$table.' WHERE id = :id');
$st->execute(array(':id', $id));
}

You can't do multiple table delete in a single query Try with foreach in PDO
$pdo = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$tables = array("table1","table2","table3","table4");
foreach($tables as $table) {
$sql = "DELETE FROM $table WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id); // $id or '75'
$stmt->execute();
}

Related

Is it possible to parametarize query that has a concatenation variable?

As learning php and sql injections, I would like to parametize my queries for safe and secure website app. however, mine does not work I try to parametize my update and select my query but I didn't achieved the goal to make the program working.
The current output is throwing an error the ? is not found
As of now here is my code, am I missing something that does not work?
<?php
//connection
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');
if (isset($_POST['qrname'])) {
$qrid = $_POST['qrid'];
//Query No. 1
$qrQuery = "SELECT * FROM scratch_cards WHERE code='$qrid' ";
$qrQuery_run = mysqli_query($connection,$qrQuery);
//Query No. 2
$qrQuery2 = "UPDATE scratch_cards SET status = 'U' WHERE code='$qrid' ";
$qrQuery_run2 = mysqli_query($connection,$qrQuery2);
$qrQuery2->bind_param("s", $qrid);
$qrQuery2->execute();
while ($qrRow = mysqli_fetch_array($qrQuery_run)) {
$txtQrvalue = $qrRow['amount'];
$txtQrstatus = $qrRow['status'];
// QUERY TO UPDATE THE VALUE
// BIND AND PARAMETIZE MY QUERY
$qrQuery3 = $db->parepare("UPDATE shopusers SET ewallet = ewallet + " . (0+?) . " WHERE id = '?' ");
$qrQuery3->bind_param("ii", $txtQrvalue, $id);
$qrQuery3->execute();
//END
}
If I'm reading your question and code right, you can reduce this down to two queries using a JOIN instead, that way you can get rid of the SELECT statement. Use prepared statements for both.
I also specified your connection's charset to UTF-8 (which you should set for your PHP and HTML headers, and your database-tables too).
<?php
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');
$connection->set_charset("utf8");
if (isset($_POST['qrname'])) {
$qrid = $_POST['qrid'];
$sql = "UPDATE scratch_cards SET status = 'U' WHERE code=?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $qrid);
$stmt->execute();
$stmt->close();
$sql = "UPDATE shopusers su
INNER JOIN scratch_cards sc
ON sc.qrid = su.code
SET su.ewallet = su.ewallet + sc.amount,
sc.status = 'U'
WHERE sc.code = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $qrid);
$stmt->execute();
$stmt->close();
}
we have the foll syntax in PDO bind param, where i have put your update query as an example and it works perfectly fine. Try searching for named parameter binding
<?php
$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';
$mysqlConnection = new \PDO('mysql:host='.$host.';dbname='.$DB, $user, $pass);
$mysqlConnection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sql = 'update info set fname = fname + :fn where id = 1';
$stmt = $mysqlConnection->prepare($sql);
$stmt->bindValue(':fn', '100');
$stmt->execute();
echo $stmt->rowCount();
?>
Is this the query you wanted to run using mysqli bind params???
<?php
ini_set('display_errors', 1);
$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';
$sql = 'update info set fname = fname + ? where id = 1';
$conn = new mysqli($host, $user, $pass, $DB);
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $val);
$val = 100;
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
exit;

PDOStatement::execute, How to execute?

How to execute this query?
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM attendancy
WHERE user_id = $user_id
AND date = '$date'";
$q = $pdo->prepare($sql);
To execute you need to use the execute function. This usage of the prepare function also is not safe, each variable should be a placeholder.
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM attendancy
WHERE user_id = ?
AND date = ?";
$q = $pdo->prepare($sql);
$q->execute(array($user_id, $date));
while($result = $q->fetch(PDO::FETCH_ASSOC)) {
print_r($result);
}

PDO not being able to return the last_insert_id

<?php
session_start();
$userid = $_SESSION['userid'];
$categorynumber=0;
$categorynumber = create_category($userid);
//keep the category number for future reference
if($categorynumber > 0){
$_SESSION['categorynumber'] = $categorynumber;
}
echo $categorynumber;
?>
echo $categorynumber prints 0
function create_category($userid)
{
// connect to database with PDO
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_DATABASE;
$dbh = new PDO($dsn, DB_USER, DB_PASSWORD);
// insert category and get the category_id
$categorynumber = 0;
$stmt = $dbh->prepare("INSERT INTO categories (userid, name) VALUES (:userid, :name);SELECT LAST_INSERT_ID();");
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->bindValue(':name', 'test7', PDO::PARAM_STR);
if ($stmt->execute())
{
$result = array();
while ($row = $stmt->fetch()) {
array_push($result, $row);
}
if (isset($result[0][0]))
$categorynumber = $result[0][0];
}
// close database and return null
$dbh = null;
return $categorynumber;
}
What am I doing wrong here, so that I cannot retrieve the last id of the created entry? How can I return the last_insert_id(); and assign it to the $_SESSION['categorynumber']??
I have managed to achieve what I wanted with the following line:
$categorynumber = $dbh->lastInsertId();
full example:
function create_category($userid)
{
// connect to database with PDO
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_DATABASE;
$dbh = new PDO($dsn, DB_USER, DB_PASSWORD);
// insert category and get the category_id
$categorynumber = 0;
$stmt = $dbh->prepare("INSERT INTO categories (userid, name) VALUES (:userid, :name);");
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->bindValue(':name', 'test7', PDO::PARAM_STR);
$stmt->execute();
$categorynumber = $dbh->lastInsertId();
// close database and return null
$dbh = null;
return $categorynumber;
}

How to use new format

I have the following query, but this one is old. There should be a new way of writing the following code. Can anyone tell me how i should write this:
$get_test = mysql_query("select test from test_table where id = '1'");
$test = mysql_result($get_test, 0);
Ik would like to write it in: MYSQLI instead of mysql.
Maybe this is what you are looking for:
Mysqli:
<?php
$strSQL = "select test from test_table where id = '1'";
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo $result["test"]."
";
}
?>
PDO:
<?php
$id = 1;
try {
#connection
$conn = new PDO('mysql:host=localhost;dbname=myDB', $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('SELECT test FROM test_table WHERE id = :id');
$data->execute(array('id' => $id));
while($rows = $data->fetch()) {
print_r($rows);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}?>
You should use PDO:
$db = new PDO("...");
$statement = $db->prepare("select test from test_table where id = :id");
$statement->execute(array(':id' => "test"));
$row = $statement->fetch();

How to avoid mysql injections using PDO

How can I avoid mysql injections? This is the PHP file I have right now
<?php
include 'config.php';
$Name = $_GET['Name'] ;
$sql = "Select * from tables where names =\"$Name\"";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->query('SET CHARACTER SET utf8');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$names = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($names) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
When I put $stmt = $dbh->query($sql); $stmt->execute(array(':name' => $name)); to the code it doesn't work. So how should I do it?
Read about pdo prepared statements
Here is an example
$stmt = $dbh->prepare("SELECT * FROM tables WHERE names = :name");
$stmt->execute(array(':name' => $name));

Categories