I can update text strings (varchar) types to my Mysql database with PDO without any problems. but with integer (int(11)) types - my PDOstatement has some big problems and also can not write the integer value to the database.
here you can see the error message I get by putting integer values for UPDATE:
ERRNO:42000 ERROR: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 'age = '800' WHERE id = '1'' at line 1
I am getting the values from $_POST like this:
foreach ($_POST['changed'] as $SubArray) {
foreach ($SubArray as $key => $value) {
if ($key === 'recid') continue;
$sql = "UPDATE clients SET $key = :value WHERE id = :recid";
$STH = $DBH->prepare($sql);
try {
$STH->execute(array(':value' => $value, ':recid' => $SubArray['recid']));
} catch (PDOException $e) {
$code = $e->getCode();
$file = $e->getFile();
$line = $e->getLine();
$msg = $e->getMessage();
echo "$file:$line ERRNO:$code ERROR:$msg";
}
}
}
echo urlencode($sql) => UPDATE+clients+SET+age+%3D+%3Avalue+WHERE+id+%3D+%3Arecid
setting up the query ($sql) like this, does the trick.
$sql = "UPDATE `clients` SET `$key` = :value WHERE id = :recid";
before and after table and column name use backticks
`
Related
I'm running Panda Resort CMS locally on XAMP, PHP 8.0.3, Mariadb/Phpmyadmin 5.1.0 so the "article" module is returning a SQLSTATE error:
1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') AND checked = 1 AND lang = 1 ORDER BY rank'
Exactly at line 28
<?php
if($article_alias == "") err404();
if($article_id > 0){
$title_tag = $article['title']." - ".$title_tag;
$page_title = $article['title'];
$page_subtitle = $article['subtitle'];
$page_alias = $article['alias'];
$publish_date = $article['publish_date'];
$edit_date = $article['edit_date'];
if(is_null($publish_date)) $publish_date = $article['add_date'];
if(is_null($edit_date)) $edit_date = $publish_date;
$result_article_file = $db->query(
"SELECT *
FROM pm_article_file
WHERE id_item = ".$article_id."
AND checked = 1
AND lang = ".DEFAULT_LANG."
AND type = 'image'
AND file != ''
ORDER BY rank
LIMIT 1");
if($result_article_file !== false && $db->last_row_count() > 0){
$row = $result_article_file->fetch();
$file_id = $row['id'];
$filename = $row['file'];
if(is_file(SYSBASE."medias/article/medium/".$file_id."/".$filename))
$page_img = getUrl(true).DOCBASE."medias/article/medium/".$file_id."/".$filename;
}
$result_tag = $db->query("SELECT * FROM pm_tag WHERE id IN (".$article['tags'].") AND checked = 1 AND lang = ".LANG_ID." ORDER BY rank");
if($result_tag !== false){
$nb_tags = $db->last_row_count();
$article_tags = "";
foreach($result_tag as $i => $row){
$tag_id = $row['id'];
$tag_value = $row['value'];
$article_tags .= $tag_value;
if($i+1 < $nb_tags) $article_tags .= ", ";
}
}
}else err404();
check_URI(DOCBASE.$page_alias);
I'm really stuck at this one any help would be appreciated. Thank you!
Be careful to check if your variables are empty before you interpolate them into an SQL query. If $article['tags'] is empty, you could end up with a query like this:
SELECT * FROM pm_tag WHERE id IN () AND checked = 1 AND lang = 123 ORDER BY rank
It's a syntax error to run an IN() expression with an empty list. There has to be at least one value inside the parentheses.
One way you can reduce this risk is to stop using string-interpolation, and start using query parameters. This is safer for several reasons, and it also makes it easier to write code because you don't have to get eyestrain counting your open-quote-close-quote-open-quote-close-quote-open-quote-close-quotes.
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.
I want to add record to a table which contain a picture. when i try to add, it shows me this error
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 ' masalah = 'dsd' AND gambar = 'kerusi.JPG'' at line 1
so, here are the code
<?php
session_start();
include("Connections/connection.php");
$date = $_POST['date'];
$masalah = $_POST ['masalah'];
$gambar = $_POST ['gambar'];
$student_id = $_POST['student_id'];
$status = 'pending';
/*session yg di call tok lecturer tu*/
$student_id = "SELECT * FROM student WHERE student_id ='".$_SESSION['student_id']."'" ;
$result=mysql_query($student_id);
$getstudentid = mysql_fetch_assoc($result);
$student_id = $getstudentid['student_id'];
/*take 3 data from rc */
$sql = "SELECT * FROM aduan WHERE date = '$date', masalah = '$masalah' AND gambar = '$gambar' ";
$rr = mysql_query($sql) or die(mysql_error());
$tt = mysql_num_rows($rr);
if($tt > 0) {
header("Location: borang_aduan2.php?error=2");
} else { /*to check tarikh*/
$tarikh_user = strtotime($date);
$tarikh_harini = strtotime(date('Y-m-d'));
if($tarikh_user < $tarikh_harini) {
//error
header("Location: borang_aduan2.php?error=1");
} else {
//$No = $num_rows+1;
/*$sql_const = mysql_query ("Select MAX(user_name)as id from lecturer")or die (mysql_error());
$rows = mysql_fetch_array ($sql_const);
$id = $rows ['id'];*/
/*insert data*/
mysql_query("INSERT INTO aduan (date, masalah, gambar, student_id )
VALUES('$date','$masalah', '$gambar','$student_id')")
or die('Error: ' .mysql_error($conn));
echo "<script type='text/javascript'>
alert('Thanks make a report!')
location.href='borang_aduan2.php'
</script>";
}
//Freeing all memory associated with it
mysql_free_result($result);
//Closes specified connection
mysql_close($conn);
}
?>
Dont use "," in between two field selection criteria. So instead of:
SELECT * FROM aduan WHERE date = '$date',
^^
Use
SELECT * FROM aduan WHERE date = '$date' AND
I am trying to run the following but am getting the following mysql error ?
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 'INSERT INTO hqfjt_chronoforms_data_addupdatelead SET f9f2ec4270a751f4f34980c325e' at line 2
<?php
$user = $_POST[cf_uid];
$form = $_POST[uid];
$date = date("d-m-Y");
$query = mysql_query("UPDATE hqfjt_chronoforms_data_addupdatelead SET $form = $date
WHERE cf_uid = $user
")
or die(mysql_error());
?>
what I am trying to do, is use the $USER to find the correct user record, then in that user record find the column $form and insert the $date into it,
EDIT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Ok this gets me halfway there, but still an error >>
<?php
$user = $_POST[cf_id];
$form = $_POST[uid];
$date = date("d-m-Y");
$query = mysql_query("UPDATE hqfjt_chronoforms_data_addupdatelead SET '".$form."' = '".$date."' WHERE cf_id = '".$user."'")
or die(mysql_error());
?>
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 ''185cfb5654aacf3038e3f26491f227356b5d768f' = '30-12-2011' WHERE cf_id = '14'' at line 1
This is not correct:
First you are trying to execute both select and insert together and second insert don't have set command ... I think you need an update command
update hqfjt_chronoforms_data_addupdatelead SET $form = $date
WHERE $user = $user
OR, I think you are trying to do something like this
INSERT INTO hqfjt_chronoforms_data_addupdatelead SELECT * FROM
hqfjt_chronoforms_data_addupdatelead WHERE $user = $user
EDIT:
Try This:
<?php $user = $_POST["cf_uid"];
$form = $_POST["uid"];
$date = date("d-m-Y");
mysql_query('UPDATE hqfjt_chronoforms_data_addupdatelead SET "$form" = "$date"
WHERE cf_uid = "$user"') or die(mysql_error()); ?>
as per your comment you'd be fine just doing a
$query = "UPDATE table SET $forms = $date WHERE cf_uid = $user";
$success = mysql_query($query);
or you can put it all into one line as well. But if you're just looking to update there's no need to SELECT ALL the data from the user. That's what the "WHERE" is for.
I am getting an unexpected T_CONSTANT_ENCAPSED_STRING error in the following SQL query:
mysql_query (UPDATE 'wp_posts' SET 'post_status' = 'publish' WHERE 'post_id' = '$id');
Can you guys see where the error might be?
Here is the full code in case it helps:
$key = 'feed';
$post_ids = array(2263, 2249);
foreach ($post_ids as $id) {
$feedurl = get_post_custom_values($key, $id);
$feedurlstr = implode($feedurl);
// Ignore - it determines whether feed is live and returns $result
LiveOrNot($feedurlstr);
if ( $result == "live" ) {
mysql_query (UPDATE 'wp_posts' SET 'post_status' = 'publish' WHERE 'post_id' = '$id');
}
elseif ( $result == "notlive" ) {
mysql_query (UPDATE 'wp_posts' SET 'post_status' = 'draft' WHERE 'post_id' = '$id');
}
endif;
}
Wrap your SQL statements in quote-marks - ".
mysql_query ("UPDATE 'wp_posts' SET 'post_status' = 'publish' WHERE 'post_id' = '$id'");
mysql_query() takes a string. PHP is looking for constants interspersed with strings, which is not valid PHP grammer.
You need to delimit your strings, ' and " are popular choices, but there is also Heredoc syntax.
Read more about strings in PHP.