Having trouble formatting my code to execute without error using sprintf() When I run the code I get this error: Parse error: syntax error, unexpected T_VARIABLE in /location on line 16
$query = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `itemname` = '$q'', $tablename);
Above is line 16 in my code. I'm assuming it is syntax related.
I am now receiving the following error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty' in /home/content/63/6563663/html/inventory/pg.php:19 Stack trace: #0 /home/content/63/6563663/html/inventory/pg.php(19): PDOStatement->execute() #1 {main} thrown in /home/content/63/6563663/html/inventory/pg.php on line 19
This is my entire code block:
<?php
$u=$_GET["u"];
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form2")) {
$amount = isset($_POST['amount']) ? $_POST['amount'] : null;
if (null != $amount) {
$user = 'username';
$pass = 'password';
$pdo = new PDO('mysql:localhost', $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
session_start();
$tablename = $_SESSION['MM_Username'];
$query = sprintf('UPDATE %s SET stock= :amount WHERE itemname= '.$u, $tablename);
$stmt = $pdo->prepare($UpdateQuery);
$stmt->bindParam('amount', $amount);
$stmt->execute();
}
}
?>
Thank you, seems my error is dealing with the PDO execution, not the query itself. If anyone has any ideas on that it would be great. Alan, I used your method for the quotes and also am running the query through mysql_real_escape_string().
Please do not build SQL queries out of variables. Use bind variables.
See http://bobby-tables.com/php.html
Try this:
$query = sprintf('UPDATE%sSETstock= :amount WHEREitemname= '.$q, $tablename);
You need to put a concatenation operator between strings and variables to combine them together. You also can get rid of the '' after $q because it is not changing the string at all.
Edit:
I believe I misread what you are trying to do. Try this instead:
$query = sprintf("UPDATE%sSETstock= :amount WHEREitemname= '$q'", $tablename);
By changing your PHP string to be within double quotes, you do not need to escape your single quotes, and $q will be expanded to its value.
Also, be sure that you run $q and $tablename through mysql_real_escape_string() to prevent SQL injection.
Like so:
$query = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `itemname` = \'$q\'', $tablename);
or
$query = sprintf("UPDATE `%s` SET `stock` = :amount WHERE `itemname` = \'$q\'", $tablename);
You can't have unescaped 's in strings delimited by '. Either unescaped "s in strings delimited by ". To escape the string delimiter you need to prepend a \ character.
Related
i did follow the solution here : Warning: pg_query(): Query failed: ERROR: syntax error at or near but i still got the following error :
Warning: pg_query(): Query failed: ERROR: column "rosmoffi" does not exist LINE 1: ... FROM public."espece" where "espece"."Code_Espece" =Rosmoffi ^
this is my code :
$conn = pg_connect($conn_string);
$query = 'SELECT * FROM public."espece" where "espece"."Code_Espece" ='.$idd ;
if (!$result = pg_query($conn, $query)){
echo pg_result_error ($conn);
return false;
}
$result = db($result);
return $result;
$query = 'SELECT * FROM public."espece" where "espece"."Code_Espece" ='.$idd ;
Do not do this. If you were to output what you get here you'd see the error, as you should from the error message. Whatever is in the variable $idd will be put into the query as is and it will not be considered a string. It's just a part of the query. So since there are no quotes it will in this case be understood as a column name.
The worst part of this is that if $idd is coming from the user think what will happen when someone sets it to 1; truncate table espece. Or something worse. Learn how to use parameters immediately.
Using parameters your code would be:
$query = 'SELECT * FROM public."espece" where "espece"."Code_Espece" =$1';
if (!$result = pg_query_params($conn, $query, array($idd))){
This way the variable is given properly to the database and there is no injection vulnerability.
NB! For those who keep saying the double quotes should be removed, no. They should not. If the column name is capitalized as Code_Espece then PostgreSQL will not recognize it without the quotes. Capitalization is usually not recommended.
$table="menu_permission";
$field = array('permission'=>$mnuprmis);
$ob->update($table,$field,'staff_id',$stfid);
public function update($table, $fields, $wherefield, $wherefieldvalues)
{
$sql = "update $table set";
foreach ( $fields as $fieldname => $sfieldvalue )
$sql .= $fieldname."= '".$sfieldvalue."',";
$sql = substr($fldquery,0,strlen($fldquery)-1);
$sql .=" where $wherefield = '$wherefieldvalues'";
$q = $this->conn->prepare($sql);
$q->execute();
return true;
}
The error
Fatal error: Uncaught exception 'PDOException' with message '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 staff_id = '1'' at line 1'
in G:\xampp\htdocs\live\Billing Suryas\model\DBConfig.php:171
Stack trace: #0 G:\xampp\htdocs\live\Billing Suryas\model\DBConfig.php(171): PDOStatement->execute()
#1 G:\xampp\htdocs\live\Billing Suryas\pages\permission_pages.php(257): Connection->update('menu_permission', Array, 'staff_id', '1')
#2 {main} thrown in G:\xampp\htdocs\live\Billing Suryas\model\DBConfig.php on line 171
There is no such freaking thing as an $fldquery
$sql = substr($fldquery,0,strlen($fldquery)-1);
^^^ ^^^
Hence your query is only
$sql .=" where $wherefield = '$wherefieldvalues'";
Which results in
where staff_id = '1' // This is your COMPLETE query
That is just one of the problems and it will be fixed when you fix the typo and put in correct variable name there. However a bigger problem will be evident if you read this
How can I prevent SQL injection in PHP?
It might have had to do with the fact that you put single quotes around numeric values, which isn't necessary and might break your query since your DB might regard it as a string instead of a number.
$table="menu_permission";
$field = array('permission'=>$mnuprmis);
$ob->update($table,$field,'staff_id',$stfid);
public function update($table, $fields, $wherefield, $wherefieldvalues)
{
//
// COMPILE QUERY
$sql = "update $table set ";
$col_values_array = array();
foreach ( $fields as $fieldname => $sfieldvalue ) {
$value = is_numeric($sfieldvalue) ? $sfieldvalue : "'$sfieldvalue'";
$col_values_array[] = "$fieldname = $value";
}
$sql .= implode("," , $col_values_array);
$sql .= " where $wherefield = '$wherefieldvalues'";
//
// EXECUTE QUERY
//$q = $this->conn->prepare($sql); --> not required when not using parametrised queries
//$q->execute(); --> not required when not using parametrised queries
$this->conn->query($sql);
return true;
}
Also consider using prepared statements to be safe against SQL injection.
I'm trying to do the simplest thing...
I have a form with 2 fields. I want to enter data in those fields and have them write that data to my db (mssql using sqlsrv driver).
Connecting to the db isn't a problem. Here's my form processor (only set up to update quantity (qnty) at the moment):
require_once 'dbconnect.php';
$partno = $_POST["partno"];
$qnty = $_POST["qnty"];
$sql = 'UPDATE WestDevDB SET LocationQty = $_POST["qnty"]';
$result = sqlsrv_query($conn,$sql) or die(sqlsrv_errors());
All I get is the error:
Notice: Array to string conversion in filepath\file.php on line 8
Array
and nothing writes.
I've tried changeing $_POST["qnty"] to $_POST["qnty"][0] thinking that would solve the issue, but it makes no difference.
Any thoughts on this?
Basic PHP Syntax 101: '-quoted strings do NOT interpolate variables. That means your query definition:
$sql = 'UPDATE WestDevDB SET LocationQty = $_POST["qnty"]';
is sending the literal characters $, _, P etc... as the value to compare LocationQty against. That also means that your query is causing a syntax error, because $_ etc... is not a valid field name, in pretty much any database under the sun.
And even if '-quoted strings DID interpolate variables:
a) you'd be wide open for sql injection attacks anyways.
b) Array keys cannot be quoted inside strings, unless you using the {} syntax:
$sql = "UPDATE ... = {$_POST['qnty']};"
or
$sql = "UPDATE ... = " . $_POST['qnty'];
You should use params to avoid sql injection and errors on string concatenations.
$qnty = $_POST["qnty"];
//sanitize $qnty ( !is_null, is_numeric, ... )
$sql = "UPDATE WestDevDB SET LocationQty = ( ?)";
$params = array( $qnty );
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
More sqlsrv_query update samples at Microsoft MSDN.
None of the answers above are answering the question. You have no WHERE statement. You are attempting to set LocationQty for every row in your database table. That's why it's not working
I am a php beginner.
I have the following script which works if I do not use _GET['version'] in the query, but works if I remove it. There is no error; I am not sure why it is not working.
<?php
// Specify your table name
$hostname = 'localhost';
$dbname = 'stats';
$table_name = 'st_stats';
$username = 'test';
$password = 'test';
try
{
$conn = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
//By default mode is silent and exception is not thrown. So I it to throw ex
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// If the query is like this no error is given but page shows up blank
$stmt = $conn->query("SELECT * FROM $table_name where version = $_GET['version']", PDO::FETCH_ASSOC);
// This works if uncomment below line instead and comment line above
//$stmt = $conn->query("SELECT * FROM $table_name", PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
echo("<h1>currently $count records</h1>");
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>
I want to access the page like this
http://www.mydomain/records.php?version=1.2
Note that version column does exit in the table
You could try to avoid a bit of sql injection here by preparing the statement properly:
$v_term = $_GET['version'];
$query = "SELECT * FROM $table_name where version = :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$v_term);
$result->execute();
Also, run the statement straight from the db if you can to make sure you are getting records back. Other than that, there is no other way to debug this for you from what you given us.
Maybe version is not an integer therefore need quotes ?
"SELECT * FROM $table_name where verion = '".$_GET['version']."'",
Anyway you are vulnerable to sql injection and also misusing PDO
You should at least bindParam/bindValue
Or use execute() and past the $_GET value
As documented under Variable parsing:
There are two types of syntax: a simple one and a complex one.
[ deletia ]
Example #8 Simple syntax example
[ deletia ]
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;
[ deletia ]
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
[ deletia ]
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
That is, you can reference associative arrays from within a double-quoted string in one of two ways:
// simple - don't quote your keys
"... $_GET[version] ..."
// complex - you may quote your keys, but must surround the expression in braces
"... {$_GET['version']} ..."
HOWEVER, you shouldn't be doing either here. You should instead be using a parameterised statement in order to prevent SQL injection attacks:
$stmt = $conn->prepare("SELECT * FROM $table_name WHERE verion = ?");
$stmt->execute([$_GET['version']]);
This doesnt work because you're trying to access $_GET['version'] an array variable within a string here
"SELECT * FROM $table_name where version = $_GET['version']", PDO::FETCH_ASSOC
placing {} around the variable will fix this one issue
$stmt = $conn->query("SELECT * FROM $table_name where verion = {$_GET['version']}", PDO::FETCH_ASSOC);
But you should also sanitize this value before you put it right int a sql statement
You have verion rather than version in your query. You're also not passing the value of $_GET['version'], you're passing the string "$_GET['version']" right into the query. Update your query to this:
$stmt = $conn->query("SELECT * FROM $table_name where version = {$_GET['version']}", PDO::FETCH_ASSOC);
Wrapping a variable that's inside a double quoted string ("") in curly braces ({}) evaluates to the value of the variable.
If you do this you will be wide open to SQL injection attacks. Be sure to sanitize the variable before you run the query, or better yet consider prepared statements.
I'm trying to use prepared statements to do a simple insert with PHP and Postgres. So far, I've done this:
<?php
$conn_string = "host=localhost port=5432"; // plus us/pw
$dbconn = pg_connect($conn_string);
$table = 'business_primary_category';
$column = 'primary_category';
$tag = 'restuarant';
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM $table WHERE $column = $1');
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("$tag"));
?>
I've taken it basically from the page on php.net, and can't figure out what I've done wrong. Do I need to install a library to use it or something. Thanks!
These are the errors I get:
Warning: pg_prepare() [function.pg-prepare]: Query failed: ERROR: syntax error at or near "$" at character 15 in /home/url **......** pdo.php on line 11
Warning: pg_execute() [function.pg-execute]: Query failed: ERROR: prepared statement "my_query" does not exist in /home/url **......** pdo.php on line 15
Warning: pg_execute() [function.pg-execute]: Query failed: ERROR: prepared statement "my_query" does not exist in /home/url **......** pdo.php on line 18
If you want your variables to be interpolated, then you need to use double quotes; else PHP treats it as a string literal. Try:
$result = pg_prepare($dbconn, "my_query", "SELECT * FROM $table WHERE $column = $1");
First thing that jumps out... Use double quotes on 'SELECT * FROM $table WHERE $column = $1'.