How to protect sql query when a php variable is empty [duplicate] - php

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'}. "'";
}
...

Related

erro by query data in php [duplicate]

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']. "'";

Using str_replace in table query in MYSQL [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
If you create a variable inside a if statement is it available outside the if statement?
(4 answers)
How to replace "if" statement with a ternary operator ( ? : )?
(16 answers)
If variable equals value php [duplicate]
(4 answers)
Closed 2 years ago.
There are a lot of examples on SO of using str_replace to modify a query that uses variables in MYSQL but I can't find one that solves my problem.
I have the following legacy query that I'm debugging written in PHP and MySQL.
Somewhat simplified it is:
$sql = "SELECT * from MOVIES WHERE cat = '$cat'";
In the event that cat has a certain value, say, "action" I want to check for "adventure";
Let's say you start with query:
$cat = "action";
$sql = "SELECT * FROM MOVIES WHERE cat='$cat'";
I'm trying to modify the query with:
$needle = "cat=".$cat;
$altcat = "adventure";
$altwhere = "cat=".altcat;
$sql = str_replace($needle,$altwhere,$sql); //NOTHING GETS REPLACED...NOT MATCHING Needle
How can I do this? I'm thinking the problem has something to do with use of spaces or apostrophes in the sql string but can't get it to work.
Thanks for any suggestions.
You want to replace "cat='".$cat."'" with "cat='adventure'", not "cat=".$cat with "cat=adventure".
(Though you are inconsistent in saying if there are spaces around the =.)
But you should not do this and should use a placeholder instead.
I would not try to do string substitution on the SQL query. Instead, just use query parameters.
$cat = 'action'; // suppose this is the input to your program
$sql = "SELECT * from MOVIES WHERE cat = ?";
if ($cat == 'action') {
$cat = 'adventure';
}
$stmt = $db->prepare($sql);
$stmt->execute( [ $cat ] );

PHP Query not working with the function I made for it [duplicate]

This question already has answers here:
How to avoid code repetition with PHP SQL prepared statements?
(2 answers)
Closed 2 years ago.
I'm trying to make a database for users to publish scripts for a game. Every single time I've had an issue using query and got it working one way or another. This time, I decided to make it a little easier to format the string for the query. Its not working. Heres my code:
function getSQLOperation($Data){
$returning = "INSERT INTO `ScriptDatabase`";
$keys = "(";
$values = ") VALUES (";
foreach ($Data as $Key => $Value){
$keys = $keys."`".$Key."`, ";
$values = $values."'".$Value."',";
}
return $returning.$keys.$values.")";
}
$values = array();
$values['Visibility'] = "Public";
$values['Name'] = "NameOfScript";
$values['Publisher'] = "UserID";
$values['Genres'] = "";
$values['PublishDate'] = Date('m-d-Y');
$values['Updated'] = $values['PublishDate'];
$values['Version'] = "1.0";
$values['Description'] = "None for now";
$values['Likes'] = "0";
$values['Dislikes'] = "0";
$values['Downloads'] = "0";
$operation = getSQLOperation($values);
mySQL table structure:
Anything I'm doing wrong here?
MySQL doesn't allow trailing commas in queries, but your query is generated as:
INSERT INTO `foo`(`bar`, `baz`,) VALUES ('x','y',)
Of note, there are much better ways to work with MySQL. Check out PDO, especially prepared statements.
I mean it. Your query is vulnerable to SQL Injection attack and that's serious.

Prevent SQL injection in php from variable array

I'm trying to make code insert data into MYSQL from arrays
my problem is, it's not protected against SQL Injection.
I searched at every where ,How can i prevent it compeletly.
I looked for this question
How can I prevent SQL injection in PHP?
but i found two answers make me rethinking again.
https://stackoverflow.com/a/8255054/6523558
Every answer here covers only part of the problem.
In fact, there are four different query parts which we can add to it dynamically a string a number an identifier a syntax keyword.and prepared statements covers only 2 of them
https://stackoverflow.com/a/60442/6523558
I looked around for something will help me and this what i found
http://www.w3schools.com/sql/sql_injection.asp
http://www.w3schools.com/sql/sql_datatypes_general.asp
But nothing helped me to prevent it completely from my code.
I'm using this code to insert array data to MYSQL.
It's prevent it by using base64.
$tbname = "some_table";
$array1 = array("one"=>"1a","two"=>"2b");
$S1["add1"] = " (";
$S1["add2"] = " VALUES (";
foreach($array1 as $k1=>$n1){
if($n1 !== ""){
$S1["add1"] .= $k1 . ", ";
$S1["add2"] .= "'" . base64_encode($n1) . "', ";
};}
$S1["add1"] = substr($S1["add1"],0,-2);
$S1["add1"] .= ")";
//if($S1["add1"] == ")"){$_SESSION["sql_msg"] = "You have to put at least one input";} else {
$S1["add2"] = substr($S1["add2"],0,-2);
$S1["add2"] .= ")";
$sql = "INSERT INTO " . $tbname . $S1["add1"] . $S1["add2"];
//if ($conn->query($sql) === TRUE) {$_SESSION["sql_msg"] = "New record created successfully";
//} else {$_SESSION["sql_msg"] = "Error: " . $sql . "<br>" . $conn->error;};}
//ref1();
echo $sql;
Based on my article (which is more focused on disclosing bad and wrong practices), An SQL injection against which prepared statements won't help
The protection from SQL injection is actually simple, and can be formulated in just two statements:
use placeholders for the every data value
whitelist everything else
Given all that, you should
whitelist your table and field names
create a query consists placeholders and filtered out table and field names
send your variable array into execute.
For this purpose first define an array with all the allowed field names
$allowed = ["one","two"];
Then out of this array you will need to to create a SET statement for the INSERT query that should look like
one = :one, two = two:
For this you need a code like this
$allowed = ["one","two"];
$params = [];
$setStr = "";
foreach ($allowed as $key)
{
if (isset($array1[$key]))
{
$setStr .= "`".str_replace("`", "``", $key)."` = :".$key.",";
$params[$key] = $_POST[$key];
}
}
$setStr = rtrim($setStr, ",");
Note that we are also getting data values into distinct array
Finally, get your query from parts (given a table name is already hardcoded in you script) and then prepare and execute it using array with values
$tbname = "some_table";
$sql = "UPDATE `$tbname` SET $setStr";
$pdo->prepare($sql)->execute($params);
I guess the best way is by using
$sql = str_getcsv($sql,";")["0"];
before the execution to prevent any extra commands

In zend, how to print a mysql query properly? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to print exact sql query in zend framework ?
In zend profiler, I can only either print the query with question markers (getQuery) or print the parameter array (getQueryParams).
Is there a way to replace all question markers, and print the real sql query?
Thanks!
Something like that should work:
$profile = $this->getQueryProfile($queryId);
$query = $profile->getQuery();
$params = $profile->getQueryParams();
foreach ($params as $par) {
$query = preg_replace('/\\?/', "'" . $par . "'", $query, 1);
}
The framework uses prepared statements so actually this is the real query - in reality its send to the database which parses it and then the params are binded to it and executed.
You can use the __toString() method.
$dbTable = new Application_Model_DbTable_TradeshowBooking();
$select = $dbTable->select();
$select->setIntegrityCheck(false);
$select->where('ends_on + INTERVAL 4 WEEK > ? ', $requestParams['ends_on']);
Zend_Registry::get('logger')->log($select->__toString(), Zend_Log::INFO);

Categories