edit I changed the code to the suggestion answer, all snippets now updated
currently I am playing around with PHP. Therefore I am trying to build a programm which can execute SQL commands. so, what I am trying is to write some functions which will execute the query. But I came to a point where I coundn't help myself out. My trouble is, for the INSERT INTO command, I want to give an array, containing the Data that shall be inserted but I simply can't figure out how to do this.
Here is what I got and what I think is relevant for this operation
First, the function I want to create
public function actionInsert($data_values = array())
{
$db = $this->openDB();
if ($db) {
$fields = '';
$fields_value = '';
foreach ($data_values as $columnName => $columnValue) {
if ($fields != '') {
$fields .= ',';
$fields_value .= ',';
}
$fields .= $columnName;
$fields_value .= $columnValue;
}
$sqlInsert = 'INSERT INTO ' . $this->tabelle . ' (' . $fields . ') VALUES (' . $fields_value . ')';
$result = $db->query($sqlInsert);
echo $sqlInsert;
if ($result) {
echo "success";
} else {
echo "failed";
}
}
}
and this is how I fil the values
<?php
require_once 'funktionen.php';
$adresse = new \DB\Adressen();
$adresse->actionInsert(array('nachname'=>'hallo', 'vorname'=>'du'));
My result
INSERT INTO adressen (nachname,vorname) VALUES (hallo,du)failed
What I wish to see
success
and of course the freshly insertet values in the database
There are a few things to consider when you are working with relational databases without using PDO:
What is the database that you are using.
It's your decision to choose from MySQL, postgreSQL, SQLite and etc., but different DBs generally have different syntax for inserting and selecting data, as well as other operations. Also, you may need different classes and functions to interact with them.
That being said, did you checkout the official manual of PHP? For example, An overview of a PHP application that needs to interact with a MySQL database.
What is the GOAL you are trying to accomplish?
It's helpful to construct your SQL first before you are messing around with actual codes. Check if your SQL syntax is correct. If you can run your SQL in your database, then you can try to implement your code next.
What's the right way to form an SQL query in your code?
It's okay to mess around in your local development environment, but you should definitely learn how to use prepared statements to prevent possible SQL injection attacks.
Also learn more about arrays in PHP: Arrays in PHP. You can use key-value pairs in a foreach loop:
foreach ($keyed_array as $key => $value) {
//use your key and value here
}
You don't need to construct your query in the loop itself. You are only using the loop to construct the query fields string and VALUES string. Be very careful when you are constructing the VALUES list because your fields can have different types, and you should add double quotes around string field values. And YES, you will go through all these troubles when you are doing things "manually". If you are using query parameters or PDO or any other advanced driver, it could be much easier.
After that, you can just concatenate the values to form your SQL query.
Once you get more familiar with the language itself and the database you are playing with, you'll definitely feel more comfortable. Good luck!
Is this inside of a class? I assume the tabelle property is set correctly.
That said, you should correct the foreach loop, that's not used correctly:
public function actionInsert($data_values) //$data_values should be an array
{
$db = $this->openDB();
if ($db) {
foreach ($data_values as $data){
// $data_values could be a bidimensional array, like
// [
// [field1=> value1, field2 => value2, field3 => value3],
// [field1=> value4, field2 => value5, field3 => value6],
// [field1=> value7, field2 => value8, field3 => value9],
// ]
$fields = Array();
$values = Array();
foreach($data as $key => $value){
array_push($fields,$key);
array_push($values,"'$value'");
}
$sqlInsert = 'INSERT INTO ' . $this->tabelle . ' (' . join(',',$fields) . ') VALUES (' . join(',',$values) . ')';
$result = $db->query($sqlInsert);
echo $sqlInsert;
if ($result) {
echo "success";
} else {
echo "failed";
}
}
}
This is a rather basic approach, in which you cycle through you data and do a query for every row, but it isn't very performant if you have big datasets.
Another approach would be to do everything at once, by mounting the query in the loop and sending it later (note that the starting array is different):
public function actionInsert($data_values) //$data_values should be an array
{
$db = $this->openDB();
if ($db) {
$vals = Array();
foreach ($data_values['values'] as $data){
// $data_values could be an associative array, like
// [
// fields => ['field1','field2','field3'],
// values => [
// [value1,value2,value3],
// [value4,value5,value6],
// [value7,value8,value9]
// ]
// ]
array_push('('.join(',',"'$data'").')',$vals);
}
$sqlInsert = 'INSERT INTO ' . $this->tabelle . ' (' . join(',',$data_values['fields']) . ') VALUES '.join(' , ',$vals);
$result = $db->query($sqlInsert);
echo $sqlInsert;
if ($result) {
echo "success";
} else {
echo "failed";
}
}
By the way dragonthought is right, you should do some kind of sanitizing for good practice even if you don't make it public.
Thanks to #Eagle L's answer, I figured a way that finally works. It is diffrent from what I tryed first, but if anyone having similar troubles, I hope this helps him out.
//get the Values you need to insert as required parameters
public function actionInsert($nachname, $vorname, $plz, $wohnort, $strasse)
{
//database connection
$db = $this->openDB();
if ($db) {
//use a prepared statement
$insert = $db->prepare("INSERT INTO adressen (nachname, vorname, plz, wohnort, strasse) VALUES(?,?,?,?,?)");
//fill the Values
$insert->bind_param('ssiss', $nachname, $vorname, $plz, $wohnort, $strasse);
//but only if every Value is defined to avoid NULL fields in the Database
if ($vorname && $nachname && $plz && $wohnort && $strasse) {
edited
$inserted = $insert->execute(); //added $inserted
//this is still clumsy and user unfriendly but serves my needs
if ($inserted) {//changed $insert->execute() to $inserted
echo 'success';
} else {
echo 'failed' . $inserted->error;
}
}
}
}
and the Function call
<?php
require_once 'funktionen.php';
$adresse = new \DB\Adressen();
$adresse->actionInsert('valueWillBe$nachname', 'valueWillBe$vorname', 'valueWillBe$plz', 'valueWillBe$wohnort', '$valueWillBe$strasse');
Related
database.php: //database class file
public function multipleInsert($table,$attrArray,$valuesArray) {
$sql = "INSERT INTO ".$table."(";
$array =[];
$appendValues = "";
$valuesInArray = "";
foreach ($attrArray as $key => $value) {
$sql.="".$value.", ";
}
$sql = substr_replace($sql,") VALUES ",strlen($sql)-2);
foreach ($valuesArray as $valArr) {
$valuesInArray.= "(";
foreach ($valArr as $key => $value) {
array_push($array, $value);
$valuesInArray.="?,";
}
$appendValues.= substr_replace($valuesInArray,"),",strlen($valuesInArray)-1);
$valuesInArray = "";
}
$appendValues = substr_replace($appendValues,"",strlen($appendValues)-1);
$sql.=$appendValues;
//die($sql);
$result = $this->executeQueryPRE($sql,$array);
return $result;
}
private function executeQueryPRE($sql,$arr) {
try{
$executeSQL = $this->Connection->prepare($sql);
print_r($executeSQL);die();
$executeSQL->execute($arr);
if($executeSQL) {
if($this->Connection->lastInsertId())
return $this->Connection->lastInsertId();
else
return true;
}
else
return false;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
sample.php // sample file which utilizing multiple insert query
require_once("database.php");
$Database = new Database;
$arr = ["ct_name","ct_num","ct_status"];
$arr1 = [["x","1234567890",1],["y","1234567890",1],["z","1234567890",1],["a","1234567890",1]];
$Database->multipleInsert("contact",$arr,$arr1);
Using PDO prepare statement, I am trying develop a dynamic multiple insert query. when I try to execute it, the values are getting inserted into table twice. I have gone for print_r($executeSQL) and die() option before executing it showed me a proper multiple insertion query as below.
PDOStatement Object ( [queryString] => INSERT INTO contact(ct_name,
ct_num, ct_status) VALUES (?,?,?),(?,?,?),(?,?,?),(?,?,?) )
why is it inserting twice and what is the reason and how can I overcome with this problem ?
Not an answer to your actual question but maybe to the actual problem you want to solve:
I don't think this string concat stuff is worth any trouble.
Takes longer for the php script to execute, pollutes the MySQL query cache, is error prone.
Therefore unless you can point to a very,very specific problem I think it loses on all points against: Just prepare a statement and execute it multiple times.
<?php
/*
table must be a valid table identifier
columns must be an array of valid field identifiers
recordData is an array of records, each itself an array of corresponding values for the fields in $columns
recordData is the only parameter for which proper encoding is taken care of by this function
*/
function foo($table, $columns, $recordData) {
$query = sprintf('
INSERT INTO %s (%s) VALUES (%s)
',
$table,
join(',', $columns) /* put in the field ids like a,b,c,d */,
join(',', array_pad(array(), count($columns), '?')) /* put in a corresponding number of ? placeholders like ?,?,?,? */
);
// resulting query string looks like INSERT INTO tablename (a,b,c,d) VALUES (?,?,?,?)
// let the MySQL server prepare that query
$stmt = $yourPDOInstance->prepare($query);
// it might fail -> check if your error handling is in place here....
// now just iterate through the data array and use each record as the data source for the prepapred statement
// this will (more or less) only transmit the statement identifier (which the MySQL server returned as the result of pdo::prepare)
// and the actual payload data
// .... as long as $yourPDOInstance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); has been set somewhere prior to the prepare....
foreach( $recordData as $record ) {
$stmt->execute( $record );
// might fail, so again: check your error handling ....
}
}
$cols = ["ct_name","ct_num","ct_status"];
$data = [
["x","1234567890",1],
["y","1234567890",1],
["z","1234567890",1],
["a","1234567890",1],
];
foo("contact", $cols, $data);
(script is tested by php -l only; no warranty)
see also: http://docs.php.net/pdo.prepared-statements
This question already has an answer here:
bulk updating a list of values from a list of ids
(1 answer)
Closed 9 years ago.
Is this the only way to use two foreach statements with arrays going into a MySQL database?
The first one will update the ot_hours field, and the second foreach will update the lieu_hours field. I tried to combine both to do one query but it kept updating with wrong values.
This is what I have right now that works but is ugly.
foreach($_POST['overtimehours'] as $key => $value) {
dbQuery("UPDATE $TABLE SET ot_hours='$value', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3)");
}
foreach($_POST['lieutimehours'] as $key2 => $value2) {
dbQuery("UPDATE $TABLE SET lieu_hours='$value2', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key2 AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3)");
}
I'm sure there's much better ways to do this. This is why I'm hoping someone can help me :)
Thanks in advance for all responses
Applied to your case, here is the adapted answer of Danny:
<?php
//first query:
$arrk = array_keys($_POST['overtimehours']);
$arrv = array_values($_POST['overtimehours']);
$id_list = implode(',', $arrk);
$whens = implode(
"\n ",
array_map(
function ($id, $value) {
return "WHEN {$id} THEN {$value}";
},
$arrk,
$arrv
)
);
$sql1 = "
UPDATE $TABLE
SET ot_hours = CASE trans_num
{$whens}
END,
ot_status=1,
ot_submitdate='$ot_submitdate'
WHERE id IN ({$id_list})
AND uid='$contextUser'
AND (ot_status=0 OR ot_status=1 OR ot_status=3)
";
//second query:
$arrk = array_keys($_POST['lieutimehours']);
$arrv = array_values($_POST['lieutimehours']);
$id_list = implode(',', $arrk);
$whens = implode(
"\n ",
array_map(
function ($id, $value) {
return "WHEN {$id} THEN {$value}";
},
$arrk,
$arrv
)
);
$sql2 = "
UPDATE $TABLE
SET lieu_hours = CASE trans_num
{$whens}
END,
ot_status=1,
ot_submitdate='$ot_submitdate'
WHERE id IN ({$id_list})
AND uid='$contextUser'
AND (ot_status=0 OR ot_status=1 OR ot_status=3)
";
//now use pdo to run sql1 and sql2
?>
At least you're willing to learn new things, that's good.
Don't assume that everything you expect to be posted is actually posted.
Use the ternary operation and the isset function to check if your posts are actually in place:
$overTimeHours = isset($_POST['overtimehours']) ? $_POST['overtimehours'] : false;
$lieuTimeHours = isset($_POST['lieutimehours']) ? $_POST['lieutimehours'] : false;
if($overTimeHours != false && $lieuTimeHours != false)
{
// Proceed ; checkpoint #1
}
else
{
// The values were not posted, do some error handling.
}
So at this point, inside of checkpoint #1, you would be doing this:
foreach($overTimeHours as $key => $value)
{
dbQuery("UPDATE $TABLE SET ot_hours='$value', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3)");
}
foreach($lieuTimeHours as $key2 => $value2)
{
dbQuery("UPDATE $TABLE SET lieu_hours='$value2', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key2 AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3)");
}
You would probably not find it ugly to run through a single for loop if you only had one array to parse through.
Now you have two arrays (obviously), so if the minimum amount of loops for one array is one for loop, then the minimum amount of loops that you need for two arrays have to be two. The arrays are UNRELATED so you can't use one to make parsing the other one easier.
Parsing through $overTimeHours with
$overTimeHours as $key => $value
assuming that you really need the keys and the values inside of the array, is the shortest thing you can do. Same story goes for lieuTimeHours
Your code is vonurable to SQL-injections.
Don't insert variables into your query like this:
SET lieu_hours='$value2'
A decent programmer (or a 12-year old kid) could easily enter something like this into your database:
yo';DROP TAbLE users;--
Or something similar, to delete data from your database. You must use prepared statements in order to prevent from being attacked with basic SQL-injections.
Prepared statements are available in most situations there are, but I highly recommend using either PDO or the mysqli syntax.
Here's an example of how you can create a PDO connection:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
Now you can init the database variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
And now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Now you can create a query that accepts prepared statements:
$query = "UPDATE :table SET ot_hours=:ot_hours, ot_status=1, ot_submitdate=:ot_submitdate WHERE trans_num=:key AND uid=:contextUser AND (ot_status=0 OR ot_status=1 OR ot_status=3);";
And you can now easily prepare it, execute your variables INTO the query WITHOUT being vonurable to sql injections (The difference is really: the non-prepared queries run COMMANDS, meanwhile the prepared ones are plain STRINGS):
$statement = $db->prepare($query); // Prepare the query.
$success = $statement->execute(array(
':table' => $TABLE,
':ot_hours' => $ot_hours,
':ot_submitdate ' => $ot_submitdate ,
':key' => $key,
':contextUser' => $contextUser
)); // Here you insert the variable, by executing it 'into' the prepared query.
if($success)
{
// Update was successful.
]
else
{
// Update was not successful, feel free to catch an PDOException $PDOexception
}
Also I note that I added a ";" at the end of your script, which is not REQUORED but I feel that it's safer, to make sure to tell that your execution is finished and you don't want anything related to follow (even though It's not from you).
I hope that I answered your question/s (and hopefully way beyond that), I hope that you'll consider what I said :) Feel free to ask if there are any questions.
Also, don't hesitate to correct me if I may have said anything incorrectly meanwhile writing this answer.
I would recommend you to use prepared statement. You should at least correctly encode other variables you use ($TABLE, ...)
$firstUpdate =
"UPDATE $TABLE
SET ot_hours=:value, ot_status=1, ot_submitdate='$ot_submitdate'
WHERE trans_num=:key
AND uid='$contextUser'
AND (ot_status=0 OR ot_status=1 OR ot_status=3)";
$secondUpdate =
"UPDATE $TABLE
SET lieu_hours=':value', ot_status=1, ot_submitdate='$ot_submitdate'
WHERE trans_num=:key
AND uid='$contextUser'
AND (ot_status=0 OR ot_status=1 OR ot_status=3)";
$db = PDO(...); // I assume here a connection managed by PDO
$stmt = $db->prepare($firstUpdate);
foreach($_POST['overtimehours'] as $key => $value) {
$stmt->execute(array(":key"=>$key,":value"=>$value);
}
$stmt = $db->prepare($secondUpdate);
foreach($_POST['lieutimehours'] as $key => $value) {
$stmt->execute(array(":key"=>$key,":value"=>$value);
}
In my opinion first thing you have to do is reduce the number of opening the connections with the DB like the following:
$query = "";
foreach($_POST['overtimehours'] as $key => $value) {
$query .="UPDATE $TABLE SET ot_hours='$value', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3) ; ";
}
foreach($_POST['lieutimehours'] as $key2 => $value2) {
$query .= "UPDATE $TABLE SET lieu_hours='$value2', ot_status=1, ot_submitdate='$ot_submitdate' WHERE trans_num=$key2 AND uid='$contextUser' AND (ot_status=0 OR ot_status=1 OR ot_status=3); ";
}
if ($query) dbQuery($query);
second and it is important, like you said combine the two arrays in one try and debug your code untill you succeed .
I am having a problem in my PHP script where values called from MySQL are being returned as strings, despite being marked in the database as int and tinyint.
This is a problem because when converting an array based on MySQL date into JSON data, values that should be integers are placed in double quotes, which is causing trouble in both Javascript and iPhone apps that use that JSON data. I am getting JSON values that look like "key" : "1", when what I want is "key" : 1.
After doing some research, it seems that it should be possible to get the values as their native type so long as one has PHP 5.3, and the mysqlnd module installed. I have 5.3.3 and phpinfo() seems to indicate I have the mysqlnd module installed and running:
mysqlnd enabled
Version mysqlnd 5.0.10 - 20111026
However, my values are still being returned as strings.
I have looked at the PHP manual entry for mysqlnd, and it's always possible I'm missing the obvious, but I don't see anything that indicates I need to do anything specific in my code to get the native values.
What exactly do I do to get my MySQL functions in PHP to give me the MySQL results in their native type?
In order to fascillitate an answer below, this is the command I use to connect to the database:
private function databaseConnect()
{
$this->mysqli = new mysqli(Database::$DB_SERVER, Database::$DB_USERNAME, Database::$DB_PASSWORD);
$this->mysqli->set_charset("utf8");
return true;
}
private function dbConnect()
{
Database::$USE_MYSQLI = extension_loaded('mysqli');
if (!$this->databaseConnect())
{
echo "Cannot Connect To The Database Server";
throw new Exception();
}
if (!$this->databaseSelectDB())
{
echo "The database server connected, but the system could not find the right database";
throw new Exception();
}
}
private function databaseQuery($query)
{
return $this->mysqli->query($query);
}
public function doQuery($query)
{
$result = $this->databaseQuery($query);
if ($result == FALSE)
{
//ErrorHandler::backtrace();
die("This query did not work: $query");
}
return $result;
}
private function getRows($table, $matches, $orderBy = array(), $limit = array())
{
$calcFoundRows = '';
if (count($limit) > 0)
{
$calcFoundRows = ' SQL_CALC_FOUND_ROWS';
}
$query = 'SELECT ' . $calcFoundRows . ' * FROM ' . $table;
if (count($matches) > 0)
{
$query .= ' WHERE ';
$keys = array_keys($matches);
$first = true;
foreach ($keys as $key)
{
if (!$first)
{
$query .= ' AND ';
}
$first = false;
// now he is safe to add to the query
// the only time this is an array is when this is called by getSelectedUsers or getSelectedArticles
// in that case it is an array of array's as the key (which is the column name) may have more than
// one condition
if (is_array($matches[$key]))
{
$firstForColumn = true;
foreach ($matches[$key] as $conditions)
{
if (!$firstForColumn)
{
$query .= ' AND ';
}
$firstForColumn = false;
// if the value is an array we generate an OR selection
if (is_array($conditions[1]))
{
$firstOr = true;
$query .= '(';
foreach ($conditions[1] as $value)
{
if (!$firstOr)
{
$query .= ' OR ';
}
$firstOr = false;
// clean this guy before putting him into the query
$this->cleanMySQLData($value);
if ($conditions[0] == Selection::$CONTAINS)
{
//$query .= 'MATCH (' . $key . ') AGAINST (' . $value . ') ';
$value = trim($value, "'");
$value = "'%" . $value . "%'";
$query .= $key . ' LIKE ' . $value;
}
else
{
$query .= $key . ' ' . $conditions[0] . ' ' . $value;
}
}
$query .= ')';
}
else
{
// clean this guy before putting him into the query
$var = $conditions[1];
$this->cleanMySQLData($var);
if ($conditions[0] == Selection::$CONTAINS)
{
//$query .= 'MATCH (' . $key . ') AGAINST (' . $var . ') ';
$var = trim($var, "'");
$var = "'%" . $var . "%'";
$query .= $key . ' LIKE ' . $var;
}
else
{
$query .= $key . ' ' . $conditions[0] . ' ' . $var;
}
}
}
}
else
{
// clean this guy before putting him into the query
$this->cleanMySQLData($matches[$key]);
$query .= $key . " = " . $matches[$key];
}
}
}
if (count($orderBy) > 0)
{
$query .= " ORDER BY ";
$first = true;
foreach ($orderBy as $orderCol)
{
if (!$first)
{
$query .= ',';
}
$query .= $orderCol;
$first = false;
}
}
if (count($limit) > 0)
{
$query .= ' LIMIT ' . $limit[0];
if (count($limit) > 1)
{
$query .= ',' . $limit[1];
}
}
$result = $this->doQuery($query);
$data = array();
while ($row = $this->databaseFetchAssoc($result))
{
$data[] = $row;
}
if (strlen($calcFoundRows) > 0)
{
$numRows = $this->databaseCountFoundRows();
$key = '^^' . $table . '_selectionCount';
Session::getSession()->putUserSubstitution($key, $numRows);
}
return $data;
}
What exactly do I do to get my MySQL functions in PHP to give me the MySQL results in their native type?
You connect to the database, then you prepare your query, execute it, bind the result and then you fetch it.
Let's do these steps line-by-line:
$conn = new Mysqli('localhost', 'testuser', 'test', 'test');
$stmt = $conn->prepare("SELECT id FROM config LIMIT 1");
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
var_dump($id); # it's an int!
This works for me. As you wrote your code is more complex, you will need to locate the place where you query the database. Check that you're using Mysqli::prepare() and if not, introduce it.
You will also need to use Mysqli_Stmt::execute() and then Mysqli_Stmt::bind_result() otherwise the (here integer) type is not preserved for that result column.
However, my values are still being returned as strings.
You are in PHP, where it does not matter that your data are int, bool, strings... if they have such a type they are called scalar data and dynamic castings will allow you to make them behave as you want.
For example, the string "12345"+"54321" will give you 66666.
If you absolutely want your data to be of a particular type, as in every language, it is not the driver's job. In Java you've got something like .getString, .getInt methods in JDBC's interfaces, in PHP you do not have as it is not very useful. You will have to cast yourself your data with intval boolval strval... functions or (int), (bool)... casting operators.
As your post said you can have it by using server-side prepared statement:
Advantages of using mysqlnd for PDO
mysqlnd returns native data types when using Server-side Prepared Statements, for example an INT column is returned as an integer variable not as a string. That means fewer data conversions internally.
With PDO
You have to put this line after your connection
$PDO->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
then, when you want to query :
$s = $PDO->prepare('yourquery');
//here, binding params
$s->bindValue('paramName','paramValue');
$s->execute();
With Mysqli
As you use mysqli, the syntax will be a little different :
Note: there is no way of client-side prepared statement so you won't need the configuration line that I put with PDO.
So your query will look like that:
$statement = $MySQli->prepare('your query');
$statement->bind_param('si', $stringParam, $intParam);
$statement->bind_result($var1, $var2 /*,...*/);
$statement->execute();
while($statement->fetch()){
//process here, result will be in var1, var2...
}
You can see that, here, there is no built-in fetchAll method.
To bind your data you need to use variables as it is not passed as value like in PDOStatement::bindValue() but by reference. Moreover the types are defined in the first arg (s for string, i for integer...)
There are no named parameters only indexed ones.
The fetch method works in a different way and needs you to call bind_result BEFORE the execute statement;
This is possible with mysqlnd, but only after you enable it. To enable it you need to call the method options and set the option to true:
$this->mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true);
It is enabled by default for prepared statements. If you use prepared statements all the time then you already have the data returned in the correct type.
$stmt = $mysqli->prepare('SELECT 1');
$stmt->execute();
$ret = $stmt->get_result();
echo gettype($ret->fetch_row()[0]);
The above code will return:
integer
However, if you used normal unprepared queries then all values are returned as strings even with mysqlnd. But you can enable the same setting to apply to unprepared queries, too.
$ret = $mysqli->query('SELECT 1');
echo gettype($ret->fetch_row()[0]);
// outputs:
// string
// Enable the same setting for unprepared queries
mysqli_options($mysqli, MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true);
$ret = $mysqli->query('SELECT 1');
echo gettype($ret->fetch_row()[0]);
// outputs:
// integer
The reason for this is the technical implementation of mysqlnd. The same applies to PDO_MYSQL as well, but in PDO this setting is enabled by default when you have emulated prepared statements switched off. There is a very good explanation by Ulf Wendel in one of the posts you linked.
This is the new default with PDO_MYSQL when compiled against mysqlnd, turning off the PDO prepared statement emulation and disabling PDO::ATTR_STRINGIFY_FETCHES. MySQL Prepared Statements use different binary communication protocol but non-prepared statements. The binary protocol avoids unecessary type casts to strings.
Julien Pauli explains the difference between textual and binary MySQL protocols in this presentation: https://www.slideshare.net/jpauli/mysqlnd
This probably is not the best answer but you can use something such as intval() to reinforce the data type. I've personally had this experience when using PDO, Mysqli, or even the old (now deprecated) mysql functions. You can run test cases with is_int() and is_string() to be 100% certain that the fetched data from the database really is a string versus and int. Sorry I couldn't be more help!
I have an array like this
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
When I do a var-dump I get this ->
{ ["phone"]=> int(111111111) ["image"]=> string(19) "sadasdasd43eadasdad" }
Now I am trying to add this to the DB using the IN statement -
$q = $DBH->prepare("INSERT INTO user :column_string VALUES :value_string");
$q->bindParam(':column_string',implode(',',array_keys($a)));
$q->bindParam(':value_string',implode(',',array_values($a)));
$q->execute();
The problem I am having is that implode return a string. But the 'phone' column is an integer in the database and also the array is storing it as an integer. Hence I am getting the SQL error as my final query look like this --
INSERT INTO user 'phone,image' values '111111111,sadasdasd43eadasdad';
Which is a wrong query. Is there any way around it.
My column names are dynamic based what the user wants to insert. So I cannot use the placeholders like :phone and :image as I may not always get a values for those two columns. Please let me know if there is a way around this. otherwise I will have to define multiple functions each type of update.
Thanks.
Last time I checked, it was not possible to prepare a statement where the affected columns were unknown at preparation time - but that thing seems to work - maybe your database system is more forgiving than those I am using (mainly postgres)
What is clearly wrong is the implode() statement, as each variable should be handled by it self, you also need parenthesis around the field list in the insert statement.
To insert user defined fields, I think you have to do something like this (at least that how I do it);
$fields=array_keys($a); // here you have to trust your field names!
$values=array_values($a);
$fieldlist=implode(',',$fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="insert into user($fieldlist) values(${qs}?)";
$q=$DBH->prepare($sql);
$q->execute($values);
If you cannot trust the field names in $a, you have to do something like
foreach($a as $f=>$v){
if(validfield($f)){
$fields[]=$f;
$values[]=$v;
}
}
Where validfields is a function that you write that tests each fieldname and checks if it is valid (quick and dirty by making an associative array $valfields=array('name'=>1,'email'=>1, 'phone'=>1 ... and then checking for the value of $valfields[$f], or (as I would prefer) by fetching the field names from the server)
SQL query parameters can be used only where you would otherwise put a literal value.
So if you could see yourself putting a quoted string literal, date literal, or numeric literal in that position in the query, you can use a parameter.
You can't use a parameter for a column name, a table name, a lists of values, an SQL keyword, or any other expressions or syntax.
For those cases, you still have to interpolate content into the SQL string, so you have some risk of SQL injection. The way to protect against that is with whitelisting the column names, and rejecting any input that doesn't match the whitelist.
Because all other answers allow SQL injection. For user input you need to filter for allowed field names:
// change this
$fields = array('email', 'name', 'whatever');
$fieldlist = implode(',', $fields);
$values = array_values(array_intersect_key($_POST, array_flip($fields)));
$qs = str_repeat("?,",count($fields)-1) . '?';
$q = $db->prepare("INSERT INTO events ($fieldlist) values($qs)");
$q->execute($values);
I appreciated MortenSickel's answer, but I wanted to use named parameters to be on the safe side:
$keys = array_keys($a);
$sql = "INSERT INTO user (".implode(", ",$keys).") \n";
$sql .= "VALUES ( :".implode(", :",$keys).")";
$q = $this->dbConnection->prepare($sql);
return $q->execute($a);
You actually can have the :phone and :image fields bound with null values in advance. The structure of the table is fixed anyway and you probably should got that way.
But the answer to your question might look like this:
$keys = ':' . implode(', :', array_keys($array));
$values = str_repeat('?, ', count($array)-1) . '?';
$i = 1;
$q = $DBH->prepare("INSERT INTO user ($keys) VALUES ($values)");
foreach($array as $value)
$q->bindParam($i++, $value, PDO::PARAM_STR, mb_strlen($value));
I know this question has be answered a long time ago, but I found it today and have a little contribution in addition to the answer of #MortenSickel.
The class below will allow you to insert or update an associative array to your database table. For more information about MySQL PDO please visit: http://php.net/manual/en/book.pdo.php
<?php
class dbConnection
{
protected $dbConnection;
function __construct($dbSettings) {
$this->openDatabase($dbSettings);
}
function openDatabase($dbSettings) {
$dsn = 'mysql:host='.$dbSettings['host'].';dbname='.$dbSettings['name'];
$this->dbConnection = new PDO($dsn, $dbSettings['username'], $dbSettings['password']);
$this->dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
function insertArray($table, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="INSERT INTO `".$table."` (".$fieldlist.") VALUES (${qs}?)";
$q = $this->dbConnection->prepare($sql);
return $q->execute($values);
}
function updateArray($table, $id, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$firstfield = true;
$sql = "UPDATE `".$table."` SET";
for ($i = 0; $i < count($fields); $i++) {
if(!$firstfield) {
$sql .= ", ";
}
$sql .= " ".$fields[$i]."=?";
$firstfield = false;
}
$sql .= " WHERE `id` =?";
$sth = $this->dbConnection->prepare($sql);
$values[] = $id;
return $sth->execute($values);
}
}
?>
dbConnection class usage:
<?php
$dbSettings['host'] = 'localhost';
$dbSettings['name'] = 'databasename';
$dbSettings['username'] = 'username';
$dbSettings['password'] = 'password';
$dbh = new dbConnection( $dbSettings );
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
$dbh->insertArray('user', $a);
// This will asume your table has a 'id' column, id: 1 will be updated in the example below:
$dbh->updateArray('user', 1, $a);
?>
public function insert($data = [] , $table = ''){
$keys = array_keys($data);
$fields = implode(',',$keys);
$pre_fields = ':'.implode(', :',$keys);
$query = parent::prepare("INSERT INTO $table($fields) VALUES($pre_fields) ");
return $query->execute($data);
}
Is there a function in PHP that adds quotes to a string?
like "'".str."'"
This is for a sql query with varchars. I searched a little, without result...
I do the following:
$id = "NULL";
$company_name = $_POST['company_name'];
$country = $_POST['country'];
$chat_language = $_POST['chat_language'];
$contact_firstname = $_POST['contact_firstname'];
$contact_lastname = $_POST['contact_lastname'];
$email = $_POST['email'];
$tel_fix = $_POST['tel_fix'];
$tel_mob = $_POST['tel_mob'];
$address = $_POST['address'];
$rating = $_POST['rating'];
$company_name = "'".mysql_real_escape_string(stripslashes($company_name))."'";
$country = "'".mysql_real_escape_string(stripslashes($country))."'";
$chat_language = "'".mysql_real_escape_string(stripslashes($chat_language))."'";
$contact_firstname = "'".mysql_real_escape_string(stripslashes($contact_firstname))."'";
$contact_lastname = "'".mysql_real_escape_string(stripslashes($contact_lastname))."'";
$email = "'".mysql_real_escape_string(stripslashes($email))."'";
$tel_fix = "'".mysql_real_escape_string(stripslashes($tel_fix))."'";
$tel_mob = "'".mysql_real_escape_string(stripslashes($tel_mob))."'";
$address = "'".mysql_real_escape_string(stripslashes($address))."'";
$rating = mysql_real_escape_string(stripslashes($rating));
$array = array($id, $company_name, $country, $chat_language, $contact_firstname,
$contact_lastname, $email, $tel_fix, $tel_mob, $address, $rating);
$values = implode(", ", $array);
$query = "insert into COMPANIES values(".$values.");";
Rather than inserting the value directly into the query, use prepared statements and parameters, which aren't vulnerable to SQL injection.
$query = $db->prepare('SELECT name,location FROM events WHERE date >= ?');
$query->execute(array($startDate));
$insertContact = $db->prepare('INSERT INTO companies (company_name, country, ...) VALUES (?, ?, ...)');
$insertContact->execute(array('SMERSH', 'USSR', ...));
Creating a PDO object (which also connects to the DB and is thus a counterpart to mysql_connect) is simple:
$db = new PDO('mysql:host=localhost;dbname=db', 'user', 'passwd');
You shouldn't scatter this in every script where you want a DB connection. For one thing, it's more of a security risk. For another, your code will be more susceptible to typos. The solution addresses both issues: create a function or method that sets up the DB connection. For example:
function localDBconnect($dbName='...') {
static $db = array();
if (is_null($db[$dbName])) {
$db[$dbName] = new PDO("mysql:host=localhost;dbname=$dbName", 'user', 'passwd');
$db[$dbName]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return $db[$dbName];
}
If you're working with an array of more than two or three elements, you should use loops or array functions rather than a long sequence of similar statements, as is done in the sample code. For example, most of your sample can be replaced with:
$array = array();
foreach ($_POST as $key => $val) {
$array[$key] = "'" . mysql_real_escape_string(stripslashes($val)) . "'";
}
Here's a more comprehensive example of creating an insert query. It's far from production ready, but it illustrates the basics.
$db = localDBconnect();
// map input fields to table fields
$fields = array(
'company' => 'company_name',
'country' => 'country',
'lang' => 'chat_language',
'fname' => 'contact_firstname',
'lname' => 'contact_lastname',
'email' => 'email',
'land' => 'tel_fix',
'mobile' => 'tel_mob',
'addr' => 'address',
'rating' => 'rating',
);
if ($missing = array_diff_key($fields, $_POST)) {
// Form is missing some fields, or request doesn't come from the form.
...
} else {
$registration = array_intersect_key($_POST, $fields);
$stmt = 'INSERT INTO `dbname`.`Companies` (`'
. implode('`, `', $fields) . '`) VALUES ('
. implode(', ', array_fill(0, count($registration), '?')) . ')';
try {
$query = $db->prepare($stmt);
$query->execute(array_values($registration));
} catch (PDOException $exc) {
// log an
error_log($exc);
echo "An error occurred. It's been logged, and we'll look into it.";
}
}
To make it production ready, the code should be refactored into functions or classes that hide everything database related from the rest of the code; this is called a "data access layer". The use of $fields shows one way of writing code that will work for arbitrary table structures. Look up "Model-View-Controller" architectures for more information. Also, validation should be performed.
Firstly, I see you're using stripslashes(). That implies you have magic quotes on. I would suggest turning that off.
What you might want to do is put some of this in a function:
function post($name, $string = true) {
$ret = mysql_real_escape_string(stripslashes($_POST[$name]));
return $string ? "'" . $ret . "'" : $ret;
}
and then:
$company_name = post('company_name');
All this does however is reduce the amount of boilerplate you have slightly.
Some have suggested using PDO or mysqli for this just so you can use prepared statements. While they can be useful it's certainly not necessary. You're escaping the fields so claims of vulnerability to SQL injection (at least in the case of this code) are misguided.
Lastly, I wouldn't construct a query this way. For one thing it's relying on columns in the companies table being of a particular type and order. It's far better to be explicit about this. I usually do this:
$name = mysql_real_escape_string($_POST['name']);
// etc
$sql = <<<END
INSERT INTO companies
(name, country, chat_language)
VALUES
($name, $country, $language)
END;
That will sufficient for the task. You can of course investigate using either mysqli or PDO but it's not necessary.
Thought I'd contribute an option that answers the question of "Is there a function in PHP that adds quotes to a string?" - yes, you can use str_pad(), although it's probably easier to do it manually.
Benefits of doing it with this function are that you could also pass a character to wrap around the variable natively within PHP:
function str_wrap($string = '', $char = '"')
{
return str_pad($string, strlen($string) + 2, $char, STR_PAD_BOTH);
}
echo str_wrap('hello world'); // "hello world"
echo str_wrap('hello world', '#'); // #hello world#
Create your own.
function addQuotes($str){
return "'$str'";
}
Don't do this. Instead use parametrized queries, such as those with PDO.
This isn't a function - but it's the first post that comes up on google when you type "php wrap string in quotes". If someone just wants to wrap an existing string in quotes, without running it through a function first, here is the correct syntax:
echo $var // hello
$var = '"'.$var.'"';
echo $var // "hello"