This question already has answers here:
update a column by subtracting a value
(2 answers)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 months ago.
i'm very confused right now, the last days the same code worked normally, yet now this error appears:
Uncaught mysqli_sql_exception: 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 '00-0.006 WHERE usersUID = 'test'' at line 1 in
the session was set in the login as the name and it would also work to just output the uid.
thanks
$QT = $_GET['number'];
$url = $_GET['url'];
$serviceid = $_GET['serviceid'];
$lastprice = $_GET['price'];
$converted_price = sprintf('%.8f', floatval($lastprice));
$devidedamount = $converted_price * $QT;
$currentcredits = $_SESSION['credits'];
$v = (float)$currentcredits - (float)$devidedamount;
if($currentcredits < $devidedamount){
header("location: ../newOrder.php?error=nobalance");
}
else{
$sqldevidecredits = "UPDATE users SET credits= ? WHERE usersUID = ? ";
$devidestm = mysqli_stmt_init($conn);
mysqli_stmt_prepare($devidestm, $sqldevidecredits);
mysqli_stmt_bind_param($devidestm, "ds", $v, $_SESSION['useruid']);
mysqli_stmt_execute($devidestm);
mysqli_query($conn, $sqldevidecredits);
}
Both $currentcredits and $devidedamount are string. You can't do arithmetic operations on strings. Convert them to numeric first. I think you can do something like that :
$currentcredits = floatval($currentcredits);
$devidedamount = floatval($devidedamount);
$sqldevidecredits = "UPDATE users SET credits= $currentcredits-$devidedamount WHERE usersUID = '" .$_SESSION['useruid']. "'";
You may subtract them first :
$v = (float)$currentcredits - (float)$devidedamount;
$sqldevidecredits = "UPDATE users SET credits= $v WHERE usersUID = '" .$_SESSION['useruid']. "'";
Related
This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 4 years ago.
I want to execute one and the same sql statement for a series of tables e.g. 37 tables.
For the table object name of each queried table I want to use a php variable named '$table'. The object names of the tables are provided in an included php file 'tables.php'.
The variable '$table' is generated repetitively from a concatenation of the string '$table' and an array '$numbers' for each table number, and put into the statement.
SQL reads the generated variable e.g. '$table1'. But I get an error from SQL Server for the FROM clause:
[SQL Server]Incorrect syntax near '$table1'.
I put the variable '$table' in brackets and quotation marks but it did not help.
Please help!
//php script one, 'tables.php':
$table1 = 'myTable1';
$table2 = 'myTable2';
...
$table37 = 'myTable37';
//php script two:
include_once('tables.php');
$numbers = range(1,37);
foreach($numbers as $number) {
$table = '$table' . $number;
$stmt = $db_conn->prepare("SELECT * FROM $table;");
$stmt->execute();
}
This is the solution provided by Hasan. The magic is to put the concat for variable '$table' in curly brackets led by $:
include_once('tables.php'); //provides table object names for variables $table1, $table2, etc., e.g. $table1 = 'mytable1_in_database';
//first number of a closed range of variables for tables to be queried
$i = 1;
//last number of closed range of variables for tables to be queried
$j = 37;
for($i=1; $i<=$j; $i++) {
$table = ${'table' . $i};
$stmt = $db_conn->prepare("SELECT * FROM $table;");
$stmt->execute();
}
You're getting error because you're using single quotes and variables can't interpreted, you may use double quotes or choose my below approach
$i = 1;
foreach($numbers as $number) {
$table = 'myTable' . $i;
//$table = "${'table' . $i}"; use it if you have already defined variables
$stmt = $db_conn->prepare("SELECT * FROM $table;");
$stmt->execute();
$i++;
if($i == 38) break;
}
As the question is now on Hold, hope you dont mind me adding a suggestion in your answer its to long for a comment.
This shoudl get you where you want to be, I hope :)
foreach($numbers as $number) {
$t = '$table' . $number;
$table = $t;
$stmt = $db_conn->prepare("SELECT * FROM $table");
$stmt->execute();
}
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
This should be a very basic error, but based on the error-description I can't seem to figure it out. Either I misunderstood some part of the concept or it's just some sign missing.
The problem arises when I try to execute a query.
This is some of the code (I think it should be enough):
//Create database connection to my server
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//All single variables
$lan = $_POST["lan"];
$botyp = $_POST["botyp"];
//All variables with min and max value
$pris = $_POST["pris"];
$prisArray = explode(",", $pris); //Splits string "minvalue, maxvalue" by delimiter "," to become array with [minvalue, maxvalue]
$prisMin = $prisArray[0];
$prisMax = $prisArray[1];
$storlek = $_POST["storlek"];
$storlekArray = explode(",", $storlek);
$storlekMin = $storlekArray[0];
$storlekMax = $storlekArray[1];
$rum = $_POST["rum"];
$rumArray = explode(",", $rum);
$rumMin = $rumArray[0];
$rumMax = $rumArray[1];
$avgift = $_POST["avgift"];
$avgiftArray = explode(",", $avgift);
$avgiftMin = $avgiftArray[0];
$avgiftMax = $avgiftArray[1];
$query = "SELECT * FROM bostader
WHERE lan = ? AND
objekttyp = ? AND
(pris >= ? AND pris <= ?) AND
(area >= ? AND area <= ?) AND
(rum >= ? AND rum <= ?) AND
(avgift >= ? AND avgift <= ?)";
$stmt = $pdo->prepare($query);
$stmt->execute([$lan, $botyp, $prisMin, $prisMax, $storlekMin, $storlekMax, $rumMin, $rumMax, $avgiftMin, $avgiftMax]); //Execute query using relevant variables
When I run this I get an error saying:
Parse error: parse error, expecting `']'' in /Library/WebServer/Documents/resultat.php on line 58
Which points to this line:
$stmt->execute([$lan, $botyp, $prisMin, $prisMax, $storlekMin, $storlekMax, $rumMin, $rumMax, $avgiftMin, $avgiftMax]);
Thank you in advance for your help.
Instead of this code
$stmt->execute([$lan, $botyp, $prisMin, $prisMax, $storlekMin, $storlekMax, $rumMin, $rumMax, $avgiftMin, $avgiftMax]);
you shuld try this one
$stmt->execute(array(
$lan,
$botyp,
$prisMin,
$prisMax,
$storlekMin,
$storlekMax,
$rumMin,
$rumMax,
$avgiftMin,
$avgiftMax
));
i have 181 fields in my database named S1, S2....S181. I want to update these fields using values from inputs WITH name="S1", .....NAME="S181".
MY CODE IS
$S1=$_POST['S1'];
...
...
$S181=$_POST['S181'];
$sql=mysqli_query($conn,"update 'cap' set S1='$S1'......S181='$S181'")
I am trying something like
for ($i = 1; $i<=181; $i++ ) {
$(S$i)=$_POST['S$i'];
$sql = mysqli_query($conn, "UPDATE `cap4a` SET
S$i='$(S$i)'
WHERE IDID=".$id) or die (mysqli_error($conn));
}
Is there something wrong in the way I use S$i, because I am getting errors:
"Parse error: syntax error, unexpected '(', expecting variable (T_VARIABLE) or '$' in C:\xampp1\htdocs\update_cap4a.php on line 5" ?
I don't think it's a good idea to run 181 queries to alter the same row as you do. Instead, run one query that makes all required changes to the row. The code below will work for you:
$id = (int)$_POST['id'];//remove (int) if id IDID is a string
$snippets = [];//holds little snippets eg: S1='value1'
for($i=1;$i<=181;$i++){
$varname = "S$i"; //S1...S181
if(!isset($_POST[$varname])) continue;
$snippets[] = " $varname='$_POST[$varname]' ";
}
$sql = '"UPDATE cap SET '.implode(",",$snippets)." WHERE IDID=$id";
$result = mysqli_query($conn,$sql) or die (mysqli_error($conn));
I don't cover it in this snippet but you need to add at least two things before using this in production:
Proper error handling, for when your query fails
Prepared statements or escaped values to protect against SQL injection
Is there something wrong in the way I use S$i
To dynamically create a variable named S10 and set it to 'value' when $i=10, do:
$varname = "S$i";
$$varname = 'value'; // $$varname can also be referred to as $S10
See Variable Variables in the docs.
I would gave done it this way:
for ($i = 1; $i<=181; $i++) {
$key = 'S'.$i;
$value = $_POST[$key];
$update[] = "`{$key}` = '".$value."'";
$sql = mysqli_query($conn, "UPDATE `cap4a` SET ".join(",",$update)."
WHERE IDID=".$id) or die (mysqli_error($conn));
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to prevent SQL injection in PHP?
I have a following MySQL query :
if($obj->{'parentId'} == null){
$parentID = 'NULL';
} else{
$parentID = $obj->{'parentId'};
}
$q = 'UPDATE tasks SET
Name = "'.$obj->{'Name'}.'",
Cls = "'.$obj->{'Cls'}.'",
parentId = '.$parentID.',
PhantomId = '.$obj->{'PhantomId'}.',
PhantomParentId = '.$obj->{'PhantomParentId'}.',
leaf = "'.$leaf.'" WHERE Id = "'.$obj->{'Id'}.'"';
The problem is, that if any of my non-string values is empty, the whole query throws error. How can I fix it crashing when for example $obj->{'PhantomId'} is empty without any aditional libs ?
Better consider to opt out to bound parameters. But if you still want to construct SQL queries use conditions
$q = "UPDATE ...";
...
if (!empty($obj->{'PhantomId'})) {
$q .= ", PhantomId = '" . $obj->{'PhantomId'}. "'";
}
...
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
my code have an error in update part, it shows for 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 '( reqdate= '2012-12-17',lat1= '26.18355762868919',long1= '50.30387832641602',lat' at line 1
and this is my code about update:
if(mysql_fetch_array($query1))
{
$datex = strtotime(date('Y-m-d H:i:s'))+36000;
$time = date('H:i:s', $datex);
$date=date('Y-m-d', $datex);
$result=mysql_query("SELECT * FROM sensorusers WHERE uid='$uid'");
mysql_query("UPDATE requests SET ( reqdate= '$date',lat1= '$lat1',long1= '$lng1',lat2= '$lat2',long2='$lng2',lat3='$lat3',long3='$lng3',lat4='$lat4',long4='$lng4',inout='$type',time='$time') WHERE sid= '$drivers'") or die(mysql_error());
$Alpha = #mysql_query($query2,$db); //Execute Query
}
just remove the parenthesis and surely it will execute, eg
UPDATE requests
SET reqdate = '$date',
lat1 = '$lat1',
long1 = '$lng1',
lat2 ='$lat2',
long2 = '$lng2',
lat3 = '$lat3',
long3 = '$lng3',
lat4 = '$lat4',
long4 = '$lng4',
`inout` = '$type', // << RESERVED KEYWORD
time = '$time'
WHERE sid = '$drivers'
INOUT is a RESERVED KEYWORD. You should escape it using backtick.
be warned that this code is vulnerable with SQL Injection, please read the article below to learn how to prevent from it,
How can I prevent SQL injection in PHP?
Syntax Error
Remove the ( and ) in your SQL.
mysql_query("UPDATE requests SET `reqdate` = '$date',lat1= '$lat1',long1= '$lng1',lat2= '$lat2',long2='$lng2',lat3='$lat3',long3='$lng3',lat4='$lat4',long4='$lng4',inout='$type',time='$time' WHERE sid= '$drivers'") or die(mysql_error());
Also, consider using PDO or mysqli_* functions instead of mysql_* functions.