Dynamic MySQL Query with PHP - php

I am looking for a way to make dynamic queries to my MySQL server. At the moment this is the code I use to update data on the server:
$deskAttr = json_decode($_POST["desk_attributes"]);
foreach($deskAttr as $key => $value) {
$sql = "UPDATE desk_attributes SET iw_standard=".$value->iw_standard.", avaya_standard=".$value->avaya_standard.", avaya_withcallid=".$value->avaya_withcallid.", avaya_withtransfer=".$value->avaya_withtransfer.", dual_screen=".$value->dual_screen.", air_conditioning=".$value->air_conditioning.", iw_obdialler=".$value->iw_obdialler." WHERE id=".$value->id;
$conn->query($sql);
}
As you can see, the SQL column names are the same as thedeskAttrkeys. I'm looking for a way to make this line a loop so, that I don't need to change this line if I were to add more columns to the MySQL table.
It would look something like this:
$deskAttr = json_decode($_POST["desk_attributes"]);
foreach($deskAttr as $key => $value) {
$sql = "UPDATE desk_attributes SET";
foreach($value as $k => $v) {
$sql .= " $k = $value->$k ,";
}
$sql .= "WHERE id=".$value->id";
}
How would I write the code above so it will actually work?
**EDIT**
Maybe it will be helpful to know that$deskAttr is an array of objects, and the name of the columns are the same as the name of the objects keys.
Here is what I mean in pseudo code:
foreach($object in $deskAttr) {
$sql = "UPDATE table SET ";
foreach($key in $object) {
if($key != "id")
$sql .= "$key = $object->$key, ";
}
$sql .= "WHERE id = $object->id;
$conn->query($sql);
}
Obviously this would add an extra comma at the end of the query before the WHERE part, but hopefully you get what I'm trying to achieve.

You can do it with slight change in your code by using PHP's implode() function.
Take a blank array, concatenate the update parameters to it.
And then if is not empty(), implode() to get string.
Updated Code:
$sql = "UPDATE desk_attributes SET ";
foreach ($deskAttr as $key => $value) {
$value = mysqli_real_escape_string($link, $value); // $links is database connection string.
$key = mysqli_real_escape_string($link, $key); // $links is database connection string.
$updtAttrs[] = $key ." = '" . $value . "'";
}
$sql .= ! empty($updtAttrs) ? implode(', ', $updtAttrs) : '';
$sql .= " WHERE id=" . $value->id;

Related

PHP prepared SQL with multiple LIKE condition

I want to do a search in a table with search words defined by a user.
I'm doing this by splitting the string an constructing the sql.
But i can't seem to make it work. It works fine, if only one word is entered, but with two or more words it's crashing.
$q = $_GET['q']; //Search word
$q = htmlspecialchars($q);
$q_exploded = explode ( " ", $q );
foreach( $q_exploded as $search_each ) {
$where .= "content LIKE ? OR ";
$bind .= "s";
$param .= "%$search_each%, ";
}
$where = rtrim($where,'OR ');
$param = rtrim($param,', ');
$sql = "SELECT ads_id FROM search_index WHERE ".$where."";
echo $sql . "<br>".$param."<br>".$bind."<br>";
$stmt = $dbconn->prepare($sql);
$stmt->bind_param($bind, $param);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['ads_id'];
}
This is my error
SELECT ads_id FROM search_index WHERE content LIKE ? OR content LIKE ?
%word1%, %word2%
ss
Warning: mysqli_stmt::bind_param(): Number of elements in type
definition string doesn't match number of bind variables
You issue is here:
$stmt->bind_param($bind, $param);
What you're doing is:
$stmt->bind_param("ss", $param);
While you may intend param to satisfy both of the strings it doesn't you need to pass a variable for each one. I would try looking into explode for this.
Someone posted an answer earlier, but deleted it again. That answer actually worked, i just needed to change from mySQLi to DPO.
Solution:
$q = htmlspecialchars($q);
$q_exploded = explode ( " ", $q );
$where = [];
$bind = [];
foreach ($q_exploded as $idx => $search_each) {
$key = ':val' . $idx;
$where[] = "content LIKE " . $key;
$bind[$key] = "%$search_each%";
}
$sql = "SELECT ads_id FROM search_index WHERE " . implode(" OR ", $where);
$stmt = $pdo_conn->prepare($sql);
$stmt->execute($bind);
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $stmt->fetch()) {
echo $row['ads_id'] . "<br>";
}

Bulk insertion in database

Following PHP code is working fine when only ONE set of array values in POST ie, on index value 0...When index value is greater than one, duplicate entries are getting inserted into the table..please help...
$sql = "INSERT INTO js (s_name, s_age, s_marks, s_school) VALUES ";
foreach($_POST as $objResult)
{
$i = 0;
foreach($objResult as $Result){
$i++;
if($i>1)// add ',' after first set of values in INSERT..
{
$sql .= ",";
}
$name = $Result['sname'];
$age = $Result['age'];
$mark = $Result['mark'];
$school = $Result['school'];
$sql .= "('".$name."','" .$age."','".$mark."','" .$school."')";
$result=$conn->query($sql);
}}
You can completely eliminate any issues with all of that iterating you have going on by doing something like this:
foreach($_POST as $objResult) {
foreach($objResult as $Result) {
$sql .= "(" . implode(', ', $Result) . "),";
}
}
$result=$conn->query($sql);
And now do you notice how I moved the query out of your loops? That makes sure that you run it properly and not on every iteration (loop) of the data.
Here is a working Example (You will have to press ctrl + enter to run the code)
You need to move the
$result=$conn->query($sql);
out of the inner loop, you are not clearing the string, so it will keep adding in the entries added already.
Thank you for your suggessions. And I changed my code as following..
$sql = "INSERT INTO js (s_name, s_age, s_marks, s_school) VALUES ";
foreach($_POST['student'] as $Result)
{
$name = $Result['sname'];
$age = $Result['age'];
$mark = $Result['mark'];
$school = $Result['school'];
$sql .= "('".$name."','" .$age."','".$mark."','" .$school."'),";
}
$sql = rtrim($sql,",");
$result=$conn->query($sql);
you can change code like this
foreach($_POST as $objResult) {
foreach($objResult as $Result) {
$sql .= "(" . implode(', ', $Result) . "),";
}
}
$result=$conn->query($sql);

SQL update with PHP arrays

Let's say i have and array like this
$array= Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
Keys from this array are name of columns in table and values are value of columns which i need to update.
I want to update the table based on keys and values.
I am using ADODB
Please help me
try this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
$sql .= $key . " = " . $value . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
and of course the WHERE clause:
$sql .= " WHERE condition = value";
you will get the string:
UPDATE table SET id = 3, name = NAME, age = 12 WHERE condition = value
L.E: You might need to add apostrophes to strings so I have to change my code to something like this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= " WHERE condition = value";
which will produce this:
UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE condition = value
L.E 2: If you want the id column in your condition, the code becomes this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if($key == 'id'){
$sql_condition = " WHERE " . $key . " = " . $value;
continue;
}
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= $sql_condition;
which will produce this result:
UPDATE table SET name = 'NAME', age = 12 WHERE id = 3
Hope this helps! :D
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
Source : https://stackoverflow.com/a/7884331/3793639
Other sources to check.
PHP SQL Update array and Simple UPDATE MySQl table from php array
You could use something like this for achieving that:
foreach($values as $value) {
if(!key_exists($value, $item)) {
return false;
}
$table->{$value} = $items[$value];
}
Assuming that the key index is always id and that adodb can use named placeholders you could do this:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$set = array();
$data = array();
while(list($key,$value)=each($array)) {
$data[':'.$key] = $value;
if($key!='id') {
$set[] = $key . ' = :' . $key;
// if no placeholders use $set[] = $key . " = '" . database_escape_function($value) . "'";
}
}
$sql = "UPDATE table SET ".implode($set, ',')." WHERE id=:id";
//$data is now Array(':id'=>'3', ':name'=>'NAME', ':age'=>'12');
//$sql is now "UPDATE table SET name=:name, age=:age WHERE id=:id";
$stmt = $DB->Prepare($sql);
$stmt = $DB->Execute($stmt, $data);
This is probably the shortest and easiest for you, you can also use something like this to achieve it:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$sql = "UPDATE table SET ";
$sql .= implode(', ', array_map(function($key, $value){
return is_numeric($value) ? "{$key} = {$value}" : "{$key} = '". mysql_real_escape_string($value). "'";
}, array_keys($array), $array));
$sql .= " WHERE id = 123";
// Result : UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE id = 123

creating a function to do standard DELETEs using prepared statments and php

I am currently going through a nettuts.com tutorial on building a twitter clone and there they have a function for deleting rows from a database and they are using the query method but i tried converting the function to a prepared statement.However I get the Invalid parameter number: parameter was not defined error.Here is the code for the function
public function delete($table, $arr){
$query = "DELETE FROM " . $table;
$pref = "WHERE ";
foreach ($arr as $key => $value) {
$query .= $pref. $key . " = " . ":" . $key;
$pref = "AND ";
}
$query .= ";";
$result = $this->db->prepare($query);
$result->execute($arr);
}
$connect = new Model();
$connect->delete("ribbits", array("user_id" => 2,
"ribbit" => "trial ribbit"
));
can someone please tell me what I am doing wrong?Thank you!
When you pass your array to ->execute(), the keys need to have the : character before them (just like they appear in the SQL query).
So, in your delete function, build the SQL query like this:
public function delete($table, $arr){
$keys = array();
$values = array();
foreach($arr as $key => $value){
$keys[] = $key . " = :" . $key;
$values[":".$key] = $value;
}
$query = "DELETE FROM " . $table . " WHERE " . implode(" AND ", $keys);
$result = $this->db->prepare($query);
$result->execute($values);
}

Passing NULL to a function designed to build a MySQL query in PHP

Language: PHP and MySQL
I have some rows in a database that have a column with a value of NULL. I have a function that builds the query when it receive a $params array. Here's the relevant piece of code in that function (to build the WHERE clause):
if (isset($params['where'])) {
$query .= "WHERE ";
$count = count($params['where']);
foreach ($params['where'] as $key => $value) {
$count--;
if ($count) {
$query .= "`$key` ".$value['sign']." '".$value['text']."' AND ";
} else {
$query .= "`$key` ".$value['sign']." '".$value['text']."' ";
}
}
}
The problem is that when I set $value['text'] to null, here's the result:
SELECT * FROM `db_profiles` WHERE `committed` IS '' LIMIT 100
If I set it to $value['text'] = 'NULL', then I get the following:
SELECT * FROM `db_profiles` WHERE `committed` IS 'NULL' LIMIT 100
Which of course produces nothing. Any ideas?
ANSWER
if (isset($params['where'])) {
$where_segment = array ();
foreach ($params['where'] as $key => $value) {
if (is_null($value['text'])) {
$where_segment[] = "`".$key."`"." IS NULL";
} else {
$where_segment[] = "`$key` ".$value['sign']." '".$value['text']."' ";
}
}
$query .= " WHERE ".implode('AND', $where_segment);
}
$string_array = array();
foreach($params['where'] as $field => $value) {
if(is_null($value)) {
$string_array[] = "`$field` IS NULL";
}
else {
$string_array[] = "`$field`='$value'";
}
}
$where_string = "WHERE ".implode(" AND ", $string_array);
$sql = "SELECT * FROM `db_profiles` $where_string";
Notice that if the $value is NULL I omit the '' marks around the NULL phrase.
Please use this query.
SELECT * FROM db_profiles WHERE committed IS NULL LIMIT 100.
Remove the single quotes.
When populating the values to the query, you'll need an explicit check for something like:
if(is_null($value)) {
$query . ' WHERE something IS NULL';
} else {
$query . ' WHERE something \'' . $value . '\'';
}
Note that when you are new to MySQL and PHP you should start to use prepared statements as soon as possible. They are most secure against SQL injection vulnerabilities and easy to use. You can start here to learn to use them.
this should help you without single quotes
SELECT * FROM `db_profiles` WHERE `committed` IS NULL LIMIT 100
you could set your variable like that to null
$value['text'] = NULL;
and then in your query
SELECT * FROM `db_profiles` WHERE `committed` IS $value['text'] LIMIT 100

Categories