PHP Multiple Value String in Single Query - php

I've got a HTML Textarea with 100-1000 of User:Password pairs each line and I want to insert them now in my database using PDO. Since I am really new to PDO I need your help with it and maybe you know some optimaziations for a faster insert or easier code.
This could be the content of my textarea:
User1:Pass1
User2:Pass2
User3:Pass3
And this is what I tried with:
$query = "INSERT INTO Refs (username,password,targetLevel,idOrder) VALUES :accounts";
$ps_insert = $db->prepare($query);
//this iy my textarea from the form
$accounts = $_POST['accounts'];
// Convert Accountaray to user:password tuples
// Write the SQL Statement of the VALUE pairs into
// an string array in this style '(user,password)'
$msg = explode("\n", $accounts);
for($i = 0; $i < sizeof($msg); $i++)
{
list($user, $pass) = explode(":", $msg[$i]);
if(!empty($user)){
$insert_parts[$i]="('" . $user . "','" . $pass . "',10,0)";
}
}
// Content of this string is: (user1,pass1,10,0), (user2,pass2,10,0), (user3,pass3,10,0)
$accountInserts = implode(',', $insert_parts);
$ps_insert->bindParam(':accounts', $insert_parts);
$ps_insert->execute();
Earlier I used the "well known" MySQL Queries, but I want to use PDO because I will use it for other things as well with common prepared statements. Thanks for the help!
Problem: The MySQL Insert doesn't work. How should I solve this? Any suggestions for (speed/code) optimizations?

The bind argument specifies a single scalar value. In your INSERT statement, the bind placeholder :account represents the value assigned to one column. You can only supply data values through a bind variable, you can't include parens and commas to be interpreted as SQL text.
If you supply a value for a bind placeholder, such as:
"('foo','bar',7,1)"
That will be interpreted as a single value, that won't be "seen" as SQL text, but just a character string, the value to be assigned to a single column.
You'd need a SQL statement that looks something like this:
INSERT INTO Refs (username,password,targetLevel,idOrder) VALUES (:v1, :v2, :v3, :v4)
And you'd need to supply a value for each bind placeholder.

Related

Php search Splitting criteria type

I have a php search form with two fields. One for $code another for '$name'.The user uses one or the other, not both.
The submit sends via $_POST.
In the receiving php file I have:
SELECT * FROM list WHERE code = '$code' OR name = '$name' ORDER BY code"
Everything works fine, however I would like that $code is an exact search while $name is wild.
When I try:
SELECT * FROM list WHERE code = '$code' OR name = '%$name%' ORDER BY code
Only $code works while $name gives nothing. I have tried multiple ways. Changing = to LIKE, putting in parentheses etc. But only one way or the other works.
Is there a way I can do this? Or do I have to take another approach?
Thanks
If you only want to accept one or the other, then only add the one you want to test.
Also, when making wild card searches in MySQL, you use LIKE instead of =. We also don't want to add that condition if the value is empty since it would become LIKE '%%', which would match everything.
You should also use parameterized prepared statements instead of injection data directly into your queries.
I've used PDO in my example since it's the easiest database API to use and you didn't mention which you're using. The same can be done with mysqli with some tweaks.
I'm using $pdo as if it contains the PDO instance (database connection) in the below code:
// This will contain the where condition to use
$condition = '';
// This is where we add the values we're matching against
// (this is specifically so we can use prepared statements)
$params = [];
if (!empty($_POST['code'])) {
// We have a value, let's match with code then
$condition = "code = ?";
$params[] = $_POST['code'];
} else if (!empty($_POST['name'])){
// We have a value, let's match with name then
$condition = "name LIKE ?";
// We need to add the wild cards to the value
$params[] = '%' . $_POST['name'] . '%';
}
// Variable to store the results in, if we get any
$results = [];
if ($condition != '') {
// We have a condition, let's prepare the query
$stmt = $pdo->prepare("SELECT * FROM list WHERE " . $condition);
// Let's execute the prepared statement and send in the value:
$stmt->execute($params);
// Get the results as associative arrays
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
The variable $results will now contain the values based on the conditions, or an empty array if no values were passed.
Notice
I haven't tested this exact code IRL, but the logic should be sound.

Prepared statement return false always

While trying to insert data into the database using prepared statement the prepared statement always returns false and not complete the connection.
I'm using this connection on cpanel (not sure if that's related) tried to change the order tried to change the data type.
$conn = mysqli_connect($servername,$username,$password,$database);
// $sql=$conn->prepare("insert into asset 'assetName'=?, 'grp' ='?' ,'Descrip' = '?' , 'enteredValue' = '?', 'depreciationRate' = '?','entrydate'='?' 'availability'= '?' ,'enteredBy' = '?' , 'updatedOn' = '?' , 'isPeriodic' = '?' , 'assetType' = '?','Frequency'='?','ExitDate'='?'");
if($sql = $conn->prepare("INSERT INTO `asset`(`id`, `assetName`, `grp`, `Descrip`, `enteredValue`, `depreciationRate`, `entrydate`, `availability`, `enteredBy`, `updatedOn`, `isPeriodic`, `assetType`, `Frequency`, `ExitDate`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")){
$sql->bind_param("sssssssssss",$name,$group,$value,$depreciation,$entryDate,$availability,$enteredBy,$updatedOn,$isPeriodic,$type,$frequency,$exitDate);
$sql->execute();
always return false and nothing has been inserted in the database.
As I said in the comments:
Well you have 14 ? and 11 s by my count. OR sssssssssss and ?????????????? Which as most of us know, is gonna throw an error as your placeholder count doesn't match your values
If you can put your data in an array you can use that array to build your query.
if($sql = $conn->prepare("INSERT INTO `asset`(`id`, `assetName`, `grp`, `Descrip`, `enteredValue`, `depreciationRate`, `entrydate`, `availability`, `enteredBy`, `updatedOn`, `isPeriodic`, `assetType`, `Frequency`, `ExitDate`) VALUES (".implode(',', array_fill(0,count($data), '?')).")")){
$sql->bind_param(str_repeat('s', count($data)),...$data);
Lets walk thought this a bit
Basically you can create your arguments with the same length as the $data with these 2 pieces of code:
implode(',', array_fill(0,count($data), '?')) //implode "?" with "," equal to the length of data
str_repeat('s', count($data)) //create 's' equal to the length of data
Then the real magic happens here with the ... "variadic" (variable length arguments):
$sql->bind_param(str_repeat('s', count($data)),...$data);
In PHP v5.6+ you can just inject the data using ... in and it will unwind it for you. Or in other words, put each array item in as a new argument.
For the fields (columns)
If you want to do the fields too, that is a bit more tricky. You have to be careful of what is in those if you put that data directly into the SQL. For example a User could edit the keys used in a $_POST request in such a way as to do SQLInjection if you just concatenate the Post Keys into the SQL.
One of the simplest ways to solve this is to have a whitelist of fields like so (matched to the column names):
//all allowed column names for this query (case sensitive)
$whitelist = ["id", "assetName", ...];
You can use array_intersect_key to retain only the data you want for the query (assuming the data has matched keys). The keys will be safe to use now in the query as they must match what is in the $whitelist.
//remove unknown keys form input data (~ retain only known ones)
//array_flip($whitelist) = ["id"=>0, "assetName"=>1, ...];
$data = array_intersect_key($_POST, array_flip($whitelist));
if($sql = $conn->prepare("INSERT INTO `asset`(`".implode("`,`", array_keys($data))."`)VALUES(".implode(',', array_fill(0,count($data), '?')).")".)){
$sql->bind_param(str_repeat('s', count($data)),...$data);
Other things
The only thing this doesn't cover is if you want all the fields in $whitelist to always be present. You can solve this with validation of the incoming data or you can merge in some empty fields to insure that all the data is present.
$default = array_fill_keys($whitelist, ''); //["id"=>"", "assetName"=>"", ...] ~ create empty "default" row
//$default['updatedOn'] = date('Y-m-d'); //you can also manually set a value
$data = array_intersect_key(
array_merge(
$default,
$_POST //["id"=>"1", ...] ~ missing assetName
), array_flip($whitelist)); //-> ["id"=>"1","assetName"=>""]
Array fill keys (similar to array fill from before) takes a list of keys, and adds a value in for each. So that gives us an array who's keys are the the values of $whitelist and an empty string for each items value. I call this a default row.
Then we merge this with our original data. Data in the first array will be overwritten by any data with matched keys for the second array ($_POST in my example). So if a key is present like id in the example above, it overwrite the empty one.
Anything not overwritten keeps the empty value from the default row we made. Then the array intersect key removes anything extra like before.
*PS I didn't test any of this so please forgive any syntax errors.
Enjoy!
You have to execute the statement once you've bound the data.
$sql->execute();
The number of parameters are also inconsistent as pointed out by the comments.
I think you don't execute your query calling the execute method :
$conn = mysqli_connect($servername,$username,$password,$database);
// $sql=$conn->prepare("insert into asset 'assetName'=?, 'grp' ='?' ,'Descrip' = '?' , 'enteredValue' = '?', 'depreciationRate' = '?','entrydate'='?' 'availability'= '?' ,'enteredBy' = '?' , 'updatedOn' = '?' , 'isPeriodic' = '?' , 'assetType' = '?','Frequency'='?','ExitDate'='?'");
if($sql = $conn->prepare("INSERT INTO `asset`(`id`, `assetName`, `grp`, `Descrip`, `enteredValue`, `depreciationRate`, `entrydate`, `availability`, `enteredBy`, `updatedOn`, `isPeriodic`, `assetType`, `Frequency`, `ExitDate`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")){
$sql->bind_param("sssssssssss",$name,$group,$value,$depreciation,$entryDate,$availability,$enteredBy,$updatedOn,$isPeriodic,$type,$frequency,$exitDate);
sql->execute();
sql->close(); // close connection

Creating a json array using concat with MySql

I'm creating a json array from MySql data using concat like this:
$id = '5705';
$sql = 'select concat("{""type:""colName"",""id"":""$id""}") as myJson from table where etc.;
$stmt = $conn->prepare($sql);
What's happening is, instead of getting data from colName from the table and the value of $id, I'm getting the result as it is in $sql. How do I break out of it and get colName and $id's value?
Current Result
{""type:""colName"",""id"":""$id""}
Desired Result
{""type:""novice"",""id"":""5705""}
//Here novice is data from colName, and 5705 is the value of $id
Please DON'T DO THAT. Trying to format data into JSON in your SQL will be fragile as encoding things into JSON is subtly more tricky that you would expect and you will inevitably get it wrong.
You should use the json_encode function in PHP. It will work reliably whereas your code will almost certainly break.
$dataArray = array();
while($statement->fetch()){
$data = array();
$data['type'] = $typeColumn;
$data['id'] = $id;
$dataArray[] = $data;
}
json_encode($dataArray, JSON_HEX_QUOT);
Also, formatting data to send to a client really shouldn't be part of an SQL query.
You need a better concatenation either in query and php
'select concat("{""type:"",colName,"",""id"":""'.$id.'""}")
Despite it is not really needed you could surround column name with backticks `
Your variables inside your string are not substituted with their values, as you got single quotes. Double quoted strings will expand variables with their values
Thus, you could invert your quotes, like this, in order to get the actual values of your variables:
$sql = "select concat('...')"

Generate Create Table Script MySQL Dynamically with PHP

I do not think that this has been posted before - as this is a very specific problem.
I have a script that generates a "create table" script with a custom number of columns with custom types and names.
Here is a sample that should give you enough to work from -
$cols = array();
$count = 1;
$numcols = $_POST['cols'];
while ($numcols > 0) {
$cols[] = mysql_real_escape_string($_POST[$count."_name"])." ".mysql_real_escape_string($_POST[$count."_type"]);
$count ++;
$numcols --;
}
$allcols = null;
$newcounter = $_POST['cols'];
foreach ($cols as $col) {
if ($newcounter > 1)
$allcols = $allcols.$col.",\n";
else
$allcols = $allcols.$col."\n";
$newcounter --;
};
$fullname = $_SESSION['user_id']."_".mysql_real_escape_string($_POST['name']);
$dbname = mysql_real_escape_string($_POST['name']);
$query = "CREATE TABLE ".$fullname." (\n".$allcols." )";
mysql_query($query);
echo create_table($query, $fullname, $dbname, $actualcols);
But for some reason, when I run this query, it returns a syntax error in MySQL. This is probably to do with line breaks, but I can't figure it out. HELP!
You have multiple SQL-injection holes
mysql_real_escape_string() only works for values, not for anything else.
Also you are using it wrong, you need to quote your values aka parameters in single quotes.
$normal_query = "SELECT col1 FROM table1 WHERE col2 = '$escaped_var' ";
If you don't mysql_real_escape_string() will not work and you will get syntax errors as a bonus.
In a CREATE statement there are no parameters, so escaping makes no sense and serves no purpose.
You need to whitelist your column names because this code does absolutely nothing to protect you.
Coding horror
$dbname = mysql_real_escape_string($_POST['name']); //unsafe
see this question for answers:
How to prevent SQL injection with dynamic tablenames?
Never use \n in a query
Use separate the elements using spaces. MySQL is perfectly happy to accept your query as one long string.
If you want to pretty-print your query, use two spaces in place of \n and replace a double space by a linebreak in the code that displays the query on the screen.
More SQL-injection
$SESSION['user_id'] is not secure, you suggest you convert that into an integer and then feed it into the query. Because you cannot check it against a whitelist and escaping tablenames is pointless.
$safesession_id = intval($SESSION['user_id']);
Surround all table and column names in backticks `
This is not needed for handwritten code, but for autogenerated code it is essential.
Example:
CREATE TABLE `table_18993` (`id` INTEGER .....
Learn from the master
You can generate the create statement of a table in MySQL using the following MySQL query:
SHOW CREATE TABLE tblname;
Your code needs to replicate the output of this statement exactly.

PHP MYSQL - empty variable fails on insert

I have an insert statement that inserts variables collected from a form POST on the previous page. If the variables from the form are not filled in it fails on insert (presumably because it is inserting an empty string...) I have the dataype set to allow NULL values - how do I insert null values if the field was left empty from the form POST?
$query = "
INSERT INTO songs (
userid,
wavURL,
mp3URL,
genre,
songTitle,
BPM
) VALUES (
'$userid',
'$wavFile',
'$mp3File',
'$genre',
'$songTitle',
'$BPM'
)
";
$result = mysql_query($query);
The exact manner depends on if you are writing the query or binding parameters to a prepared statement.
If writing your own, it would look something like this:
$value = empty($_POST['bar']) ? null : $_POST['bar'];
$sql = sprintf('INSERT INTO foo (bar) VALUES (%s)',
$value === null ? 'NULL', "'".mysql_real_escape_string($value)."'");
$result = mysql_query($sql);
The main point is that you need to pass in the string NULL (without quotes) if the value should be null and the string 'val' if the value should be "val". Note that since we are writing string literals in PHP, in both cases there is one more pair of quotes in the source code (this makes one pair in the first case, two pairs in the second).
Warning: When inserting to the database directly from request variables, it is very easy to be wide open to SQL injection attacks. Do not be another victim; read about how to protect yourself and implement one of the universally accepted solutions.
For what I understand when something is not filled the post variable is not set as an empty value but rather not set at all so in php you'd do for example:
$genre = isset($_POST['genre']) ? $_POST['genre'] : NULL;
Here's how I do it. I don't like sending anything to an SQL query right from POST (always sanitize!) in the following cas you just run through the POST vars one by one and assign them to a secondary array while checking for 0 length strings and setting them to NULL.
foreach ($_POST as $key => $value) {
strlen($value)=0 ? $vars[$key] = NULL : $vars[$key] = $value
}
Then you can build your SQL query from the newly created $vars[] array.
As Jon states above, this would be the place to also escape strings, strip code and basically do all your server side validation prior to data being inserted into the db.

Categories