Pass key value in mysql - php

Is this query right? Can i pass array key like this?
mysqli_query("UPDATE subjects SET has_notes = 1 WHERE sub_id = '$notes_data['sub']'");
If not please help me with a solution.
Thanks in advance

Im surprised no one told you to prepare that query:
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "UPDATE subjects SET has_notes = 1 WHERE sub_id = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "i", $notes_data['sub']);
/* execute query */
mysqli_stmt_execute($stmt);
}
or the object oriented way:
/* create a prepared statement */
if ($stmt = $mysqli->prepare("UPDATE subjects SET has_notes = 1 WHERE sub_id = ?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $notes_data['sub']);
/* execute query */
$stmt->execute();
}
Please read up on mysqli::prepare/mysqli_prepare

mysqli_query("UPDATE subjects SET has_notes = 1 WHERE sub_id = '".$notes_data['sub']."'");

A simply solution can be this:
mysqli_query('UPDATE subjects SET has_notes = 1 WHERE sub_id = ' . $notes_data['sub']);
Note: this solution is correct if sub_id is an integer field and $notes_data['sub'] is an integer too
otherwise:
mysqli_query("UPDATE subjects SET has_notes = 1 WHERE sub_id = '" . $notes_data['sub'] ."'");

You need to use { and } to enclose the value you're including:
mysqli_query("UPDATE subjects SET has_notes = 1 WHERE sub_id = '{$notes_data['sub']}'");
I'd encourage you, however, to seriously consider writing using MySQLi's prepared statements rather than building up the query like this - if the $notes_data['sub'] variable has come from the web then you'll be at serious risk of an SQL injection vulnerability.
Why not do something like this:
$stmt = mysqli_prepare($link, 'UPDATE subjects SET has_notes = 1 WHERE sub_id = ?');
mysqli_stmt_bind_param($stmt, 's', $notes_data['sub']);
mysqli_stmt_execute($stmt);

Related

How to add an int value (+1) in query php

I want to +1 a value because when I return the book, this query will run and return the book but it doesn't return the value just keep subtracting the value of book thanks for helping me
$id=$_GET['id'];
$book_id = $_GET['book_id'];
if(isset($id)){
$b=mysqli_query($dbcon, "SELECT * FROM book WHERE book_id='$book_id'");
$row=mysqli_fetch_array($b);
$copies=$row['book_copies'];
$new = $copies++;
mysqli_query($dbcon,"UPDATE book ON book_copies = $new");
}
You can simply do
UPDATE book SET book_copies = book_copies + 1
WHERE book_id='$book_id'
Although this leaves your script at risk of SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements
You should be preparing and parameterising the query like this
$sql = "UPDATE book SET book_copies = book_copies + 1
WHERE book_id=?";
$stmt = $dbcon->prepare($sql);
$stmt->bind_param('i', $_GET['id']); // assuming integer here
$res = $stmt->execute();
if (! $res ) {
echo $dbcon->error;
exit;
}
You are using the update statement wrong it would something like this:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
In your case you should try something like:
"UPDATE book SET book_copies=$new WHERE book_id='$book_id'"

Can I redefine the same prepared statement?

I have a script that sends more than 10 queries of all CRUD types on 5 tables (some of the SELECTs with JOINs). Originally, I used mysqli_* functions for all those. Now, to improve security, I am porting the code to use prepared statements.
I have no previous experience using prepared statements and I have some doubts about what can and cannot be done. For instance lets say I start by a SELECT query, then have an UPDATE and finally an INSERT.
My question is this:
Should I repeat the mysqli_stmt_init and mysqli_stmt_close for each query, or could I initiate once before the first query, prepare a statement for each query and use it and finally close it after all queries are done with? In other words, is method 2 OK, or should I stick to method 1?
Method 1 - No reuse
// SELECT
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "SELECT on table 1 and table 2");
...
mysqli_stmt_close($stmt);
// UPDATE
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "UPDATE on table 3");
...
mysqli_stmt_close($stmt);
// INSERT
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "INSERT INTO table 4");
...
mysqli_stmt_close($stmt);
Method 2 - Reusing statement
// INIT
$stmt = mysqli_stmt_init($link);
// SELECT
mysqli_stmt_prepare($stmt, "SELECT on table 1 and table 2");
...
// UPDATE
mysqli_stmt_prepare($stmt, "UPDATE on table 3");
...
// INSERT
mysqli_stmt_prepare($stmt, "INSERT INTO table 4");
...
// CLOSE
mysqli_stmt_close($stmt);
There is no need for stmt_init() or stmt_close(), mysqli_prepare() returns a stmt object and PHP handles the cleaning, the correct order is mysqli_stmt::prepare => mysqli_stmt::bind_param => mysqli_stmt::execute.
$mysqli = new mysqli( "host", "user", "pass", "db" );
$stmt = $mysqli->prepare( "SELECT * FROM table WHERE id = ?" );
$stmt->bind_param( "i", $id );
$id = 5;
$stmt->execute();
You can execute the same statement multiple times with different params, for example:
$stmt = $mysqli->prepare( "SELECT * FROM table WHERE id = ?" );
$stmt->bind_param( "i", $id );
$id = 5;
$stmt->execute(); // executed: SELECT * FROM table WHERE id = 5
$id = 3;
$stmt->execute(); // executed: SELECT * FROM table WHERE id = 3
But in case of different statements you must prepare each statement separately.
Yes, method 2 is ok.
There is no need to finally close it either, as it will be closed when your script ends.

MySQL can't accept numbers variable

I'm facing this weird problem. The code below does not work. I only get 0 from Count. Expected output is 12 from my 12 rows.
echo $userid = $row['userid']; // output is 130
mysqli_query($con, "SELECT COUNT(*) AS count FROM client WHERE userid = $userid");
However if I replace $userid variable with integer, it will work:
echo $userid = $row['userid']; // output is 130
mysqli_query($con, "SELECT COUNT(*) AS count FROM client WHERE userid = 130");
UPDATE:
$row['userid'] value was taken from other column with the column type as int.
I need to use variable in query. Please help me and thanks in advance.
UPDATE:
So I test with the code below where I assign 130 to $test. It works.
$test = 130;
mysqli_query($con, "SELECT COUNT(*) AS count FROM client WHERE userid = $test");
I guess it has something to do with parameter being of string type, where you need an integer. Also 'count' is a reserved word which may cause an error, not handled by your code. Need to backtick that also.
I suggest to use prepared statements. It is safer, better practice, and hopefully will solve your issue. Example:
$userid = $row['userid'];
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT COUNT(*) AS `count` FROM client WHERE userid =?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "i", $userid);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
Documentation:
http://php.net/manual/en/mysqli.prepare.php
This is pretty awkward:
echo $userid = $row['userid']; // output is 130
Go ahead and get rid of that echo statement.

How to bind post variables

just a quick question about binding in php
I know if you do something like
$select = update my_table set name ='".$posted_name.'" where id=1;
and that is subjected to sql injection
but how will you bind the query below
$select = update my_table set name ='".$posted_name[$a].'" where id=1;
IN my bind array this is how I am binding anything without [$a]
for any example with the first statement I am doing
$select = update my_table set name =:p_update_name where id=1;
$bind_update = array('p_update_name' => $t_update_name);
Try like this:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
you don't have to make all the names equal.
$select = "update my_table set name =:whatever where id=1";
$bind_update = array('whatever' => $random_variable);
will do. so it can be any variable you can think of. As long as it's scalar variable though

Not able to update rows using PDO

When I run the following code:
// Loop through each store and update shopping mall ID
protected function associateShmallToStore($stores, $shmall_id) {
foreach($stores as $store_id) {
$sql .= 'UPDATE my_table SET fk_shmallID = :shmall_id WHERE id = :store_id';
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':shmall_id', $shmall_id);
$stmt->bindParam(':store_id', $store_id);
$stmt->execute();
}
}
I get the following message:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters
I've also tried the following without success (without $stmt->bindParam):
$stmt->execute( array($shmall_id, $store_id));
I don't understand what I'm doing wrong.
UPDATE
I've updated my code to reflect what I actually got in my source code. There should not be any typos here.
UPDATE 2
I tried this, but I still get the same error message.
protected function associateShmallToStore($stores, $shmall_id) {
$i = 0;
$sql .= "UPDATE sl_store ";
foreach($stores as $store_id) {
$i++;
$sql .= 'SET fk_shmallID = :shmall_id, lastUpdated = NOW() WHERE id = :store_id_'.$i.',';
}
$sql = removeLastChar($sql);
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':shmall_id_'.$i, $shmall_id);
$i = 0;
foreach($stores as $store_id) {
$i++;
$stmt->bindParam(':store_id_'.$i, $store_id);
}
$stmt->execute();
}
This is the output of the SQL query:
UPDATE sl_store
SET fk_shmallID = :shmall_id, lastUpdated = NOW() WHERE id = :store_id_1,
SET fk_shmallID = :shmall_id, lastUpdated = NOW() WHERE id = :store_id_2
UPDATE 3
The code I endet up using was this:
foreach($stores as $store_id) {
$sql = "UPDATE sl_store SET fk_shmallID = :shmall_id WHERE id = :store_id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':shmall_id', $shmall_id);
$stmt->bindParam(':store_id', $store_id);
$res = $stmt->execute();
}
It's just as the error says, you have mixed named and positional parameters:
:name (named)
:person_id (named)
? (positional)
More than that, you have the named parameter :person_id, but you're binding to :id.
These are your parameters, I'll call them P1, P2 and P3:
UPDATE my_table SET name = :name WHERE id = :person_id ?
^ P1 ^ P2 ^ P3
And this is where you bind them:
$stmt->bindParam(':name', $name); // bound to P1 (:name)
$stmt->bindParam(':id', $person_id); // bound to nothing (no such param :id)
You probably want to bind the second parameter to :person_id, not to :id, and remove the last positional parameter (the question mark at the end of the query).
Also, each iteration through the foreach loop appends more to the query, because you're using the concatenation operator instead of the assignment operator:
$sql .= 'UPDATE my_table SET name = :name WHERE id = :person_id ?';
You probably want to remove that . before =.
For more about this, take a look at the Prepared statements and stored procedures page in the PDO manual. You will find out how to bind parameters and what the difference is between named and positional parameters.
So, to sum it up:
Replace the SQL line with:
$sql = 'UPDATE my_table SET name = :name WHERE id = :person_id';
Replace the second bindParam() call with:
$stmt->bindParam(':person_id', $person_id);
Try:
$sql = 'UPDATE my_table SET name = :name WHERE id = :id';

Categories