MYSQL - How to update a value? - mysql

After selecting the record with the current KEY and PROGRAM, I want to update the 'log_info' field for that CURRENT record, inputting the date/time. However, I keep getting the 'die error' for the update code.
ERROR CODE:
"Warning: mysql_query() expects parameter 1 to be string"
(for the "$log_info = mysql_query($query,"UPDATE..." code)
Snippet
$query = mysql_query("SELECT *
FROM `product_keys`
WHERE `serial_key` = '".$key."'
AND `program` = '".$prog."' LIMIT 1") or die('error selecting');
// UPDATE 'log_info' value to the latest date and time
$time = time();
$log_time = date('Y-m-d g:i:sa',$time);
$log_info = mysql_query($query,"UPDATE 'product_keys'
SET 'log_info' = '".$log_time."'
WHERE `serial_key` = '".$key."'
AND `program` = '".$prog."' LIMIT 1") or die('log error');

Try this line:
$log_info = mysql_query($query,"UPDATE `product_keys` SET `log_info` = '".$log_time."' WHERE `serial_key` = '".$key."' AND `program` = '".$prog."' LIMIT 1") or die(mysql_error());
Using mysql_error() you can catch specific error of query.
See The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

You have ' around the column name 'log_info' and the table name 'product_keys'. That should be backticks.

update query will be like this
$log_info = mysql_query("UPDATE 'product_keys'
SET 'log_info' = '".$log_time."'
WHERE `serial_key` = '".$key."'
AND `program` = '".$prog."'
LIMIT 1") or die('log error');
because mysql_query function accept 2 Parameters, first Parameter should be sql query , second Parameter is optional that is MySQL connection.

Related

Whats wrong with my query, should i use WHERE?

So, what am i doing wrong?
This query:
$query = "INSERT INTO table1 (art_nr, article, balance, list_type)
VALUES('$art_nr', '$article', '$balance', '$list_type')
ON DUPLICATE KEY UPDATE balance = sum(balance + '$quantity_ordered');
UPDATE table2 SET list = 'History' WHERE id = '$id'";
Will give me this error:
Failed to run query: SQLSTATE[HY000]: General error: 1111 Invalid use
of group function
This query:
$query = "INSERT INTO table1 (art_nr, article, balance, list_type) VALUES('$art_nr', '$article', '$balance', '$list_type')
ON DUPLICATE KEY UPDATE balance = sum(balance + '$quantity_ordered') WHERE art_nr = '$art_nr';
UPDATE table2 SET list = 'History' WHERE id = '$id'";
Will give me this error:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'WHERE art_nr = 'S2Bygel'; UPDATE purchase_orderlist SET
list' at line 2
UPDATE
This was my first query. With Params:
//SECURITY
$params_array= array(
':id' => $_POST['formData']['id'],
':art_nr' => $_POST['formData']['art_nr'],
':article' => $_POST['formData']['article'],
':quantity_ordered' => $_POST['formData']['quantity_ordered'],
':list_type' => $_POST['formData']['list_type']
);
//QUERY
$query = "INSERT INTO table1 (art_nr, article, balance, list_type) VALUES (:art_nr, :article, :balance, :list_type)
ON DUPLICATE KEY UPDATE balance = balance + VALUES(:quantity_ordered) WHERE art_nr = :art_nr;
UPDATE table2 SET list = 'History' WHERE id = :id";
The problem with this query is that im running two querys at the same time. and then i will get this error:
Failed to run query: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
SUCCESS
I had to use prepared statements and separate my two querys:
//SECURITY
$params_array= array(
':art_nr' => $_POST['formData']['art_nr'],
':article' => $_POST['formData']['article'],
':quantity_ordered' => $_POST['formData']['quantity_ordered'],
':list_type' => $_POST['formData']['list_type']
);
//QUERY
$query = "INSERT INTO table1
(art_nr, article, balance, list_type)
VALUES (:art_nr, :article, :quantity_ordered, :list_type)
ON DUPLICATE KEY UPDATE
art_nr = art_nr, article = article, balance = balance + :quantity_ordered, list_type = list_type";
//EXECUTE
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($params_array);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
//SECURITY
$params_array= array(
':id' => $_POST['formData']['id']
);
//QUERY
$query = "UPDATE table2 SET list = 'History' WHERE id = :id";
//EXECUTE
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($params_array);
echo "success";
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
You just want to add the value of $quantity_ordered to balance for the row? Then you don't need the sum() aggregation function. Just the + operator is enough.
But it seems like you're doing this in a host language like PHP. You should urgently learn to use parameterized queries! Do not use string concatenation (or interpolation) to get values in a query. That's error prone and may allow SQL injection attacks against your application.

get the last id of the query with pdo php [duplicate]

I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

SQL - SELECT with WHERE statement return false despite present field in table

I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";

Trouble Inserting An Array of Information into a MySQL Database

I am having an issue with inserting an array of information into a mysql database. Basically I built a sortable gallery similar to Facebook's photo albums that can be arranged by moving the div to a new spot with jquery's sortable function.
I am using Ajax to call a php file which will inser the new order of the div's into the DB. The information is being passed correctly, it is just not being inserted correctly.
The error I am receiving is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Array' at line 1
The Php code is:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
If I remove the mysql_query function and just do a print_r, I get:
Array
(
[0] => UPDATE table SET order = '0' WHERE id = '2'
[1] => UPDATE table SET order = '1' WHERE id = '4'
[2] => UPDATE table SET order = '2' WHERE id = '3'
[3] => UPDATE table SET order = '3' WHERE id = '1'
[4] => UPDATE table SET order = '4' WHERE id = '5'
[5] => UPDATE table SET order = '5' WHERE id = '6'
)
This is the first time I have tried to do something like this. Any help would be great.
Thank you in advance for the help!
In mysql_query($sql) $sql is an array, therefore it's value is simply Array. When you assign $sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'"; simply make this line $sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";. That should solve your problem.
EDIT:
You can leave the [] and simply remove the mysql_query from where it is. After your foreach list item, add this:
foreach($sql as $query) {
mysql_query($query);
}
Sounds like there is some confusion about what the [] operator does. You use [] when you want to append an element to the end of an existing array.
For example:
$sql = array();
$sql[] = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will produce the error you are seeing
Versus:
$sql = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will work
You should rewrite your code as such:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
That will do what you are intending. However, this is still not a good idea, since you are passing untrusted $_GET data directly to the database. I could, for example, call your script with a string like:
http://yoursite.com/yourscript.php?listItem=1'%3B%20DROP%20TABLE%20yourtable%3B
Since the value of listItem is going directly to the database -- and the $item >= 1 check is insufficient, since PHP will evaluate a string as an integer if it begins with numeric data -- all I have to do is add a single quote to terminate the previous query, and I am then free to inject whatever SQL command I'd like; this is a basic SQL injection attack. Whenever you write database-touching code, you should cleanse any input that might be going to the database. A final version of your code might look like:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) { // this check may or may not be needed depending on its purpose
$sql = 'UPDATE table SET order = "' . mysql_real_escape_string($position) . '" WHERE id = "' . mysql_real_escape_string($item) . '"';
mysql_query($sql) or die(mysql_error());
}
}
There are other ways to cleanse input data as well, that is just one of them. Hope that helps.

Why is my SQL UPDATE statement not working in a loop?

The update statement in example is not working all the time even though the where clause is true. The database is MYSQL innodb. Would that cause some sort of locking ?? This is so weird.
<?php
$query = 'SELECT id FROM TABLE1';
$result = db_query($query);
while($row = db_fetch_array($result)) {
//do some processing
db_query('UPDATE {TABLE1} SET updated = "1" WHERE id = "%s"',$row['id']);
}
?>
The syntax is wrong - MySQL doesn't use curly brackets:
db_query('UPDATE `TABLE1` SET updated = "1" WHERE id = "%s"',$row['id']);