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);
}
Related
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;
I have a some problem here, where I want to update the data in CRUD, the data even adding new(like insert).
Have any idea to solve it? Thanks.
There is my code,
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE customers
SET name = ?, email = ?, address = ?
WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$address));
Database::disconnect();
header("Location: index.php");
}
}else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM customers WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
Database::disconnect();
}
binding id as well in the prepared statement
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$values = array($name,$email,$address);
if($id) {
$sql = "UPDATE customers
SET name = ?, email = ?, address = ?
WHERE id = ?";
$values[] = $id;
} else {
$sql = "INSERT INTO customers (name, email, address)
VALUES (?,?,?)";
}
$q = $pdo->prepare($sql);
$q->execute($values);
Database::disconnect();
header("Location: index.php");
}
}else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM customers WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
Database::disconnect();
}
See line 8 (leave out the **)
edit
added a insert query for the case $id is empty
based on understanding of a comment
number of bound variables does not match number of tokens
$sql = "UPDATE customers
SET name = ?, email = ?, address = ?
WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$address));
You have four tokens ? there should be four parameters, as of :
$q->execute(array($name,$email,$address,$id));
and pay attention not put header("Location: index.php"); in the same file as index.php, because that will cycle and you will get an error like:
your webhost redirected you too many times
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();
}
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();
This is my code. I created a code that was a update of news
But at moment not show errors. But does not make a update....
<?php
require("common.php");
global $host, $dbname, $username, $password, $options;
$conteudox = $_POST['conteudo'];
//$imagem = $_['imagem'];
if(isset($_POST['conteudo']))
{
$dbh = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password);
$sql = "UPDATE news SET conteudo = '{$conteudox}' WHERE id = '{$id_cont}'";
$count = $dbh->exec($sql);
echo "ssssss";
$dbh = null;
}
else
{
echo "nnnnn";
}
?>
try again with
if(isset($_POST['conteudo']))
{
$dbh = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("UPDATE news SET conteudo = ? WHERE id = ?");
// where's $id_cont comming from?
$count = $stmt->execute(array($_POST['conteudo'],$id_cont));
echo "ssssss";
$dbh = null;
}
else
{
echo "nnnnn";
}
Check all your variables and try to use :
$sql = "UPDATE news SET conteudo = :conteudox WHERE id = :id_cont";
$dbh->prepare($sql);
$count=$dbh->execute(array(':conteudox'=>$conteudox,
':id_cont'=>$id_cont));