php function array argument manipulation - php

i am making insert function that takes $table argument and $cols(as array)argument.
it inserts into given table given values:
$db->query("insert into $table({$cols[0]},{$cols[1]}) values('{$_POST[{$cols[0]}]}','{$_POST[{$cols[1]}]})");
this is all nice except i don't how long array is. how to do this??

One thing you haven't done is escaped the SQL using the correct escaping mechanism.
$postCols = $_POST['cols'];
foreach($postCols as &$col) {
$col = '"' . mysql_real_escape_string($col) . '"';
}
$db->query("insert into $table(" . implode(',', $cols) . ") values(" . implode(',', $postCols . ");

I would just use some foreach loops
<?php
$sql = "INSERT INTO $table (";
foreach ($cols as $col)
$sql .= "`$col`,";
$sql = substr($sql,0,-1);
$sql .= ") VALUES(";
foreach ($cols as $col)
$sql .= "'".$_POST[$col]."',";
$sql = substr($sql,0,-1);
$sql .= ");";
echo $sql;
?>

Related

Dynamic amount of bindParam

So I am trying to make an undetermined amount of bindParam calls within a foreach, but for some reason it fails. I know the $sql variable is working fine, but I am pretty sure it is failing at the bindParam. Is there any reason for this?
$sql = "INSERT INTO " . $row1["rand"] . " (" . $areas . ") VALUES (" . $vals . ")";
echo $sql;
$entry2 = $conn->prepare("'".$sql."'");
//echo "swag";
foreach($splitHeader as $element){
if(strlen($element)>0) {
$thisVal = "':" . $element . "'";
$entry2->bindParam($thisVal,$_POST[$element]);
}
}
$entry2->execute();
The number of parameters that you define in the query must match the number of parameters that you bind.
You would need to loop twice trough your data : once to dynamically construct a sql statement (that you can then prepare), and then a second time to bind the parameters, before finally calling execute.
Here is an adaptation of your code that demonstrates the principle :
$cols = "";
$vals = "";
foreach( $splitHeader as $element ) {
if( strlen($element) > 0 ) {
if ( strlen($cols) > 0 ) {
$cols .= ", ";
$vals .= ", ";
}
$cols .= $element;
$vals .= "?";
}
}
$sql = "INSERT INTO " . $row1["rand"] . " (". $cols . ") VALUES(". $vals . ")";
echo $sql;
$sth = $conn->prepare($sql);
$i = 1;
foreach($splitHeader as $element){
if( strlen($element) > 0 ) {
$sth->bindParam( $i, $_POST[$element] );
$i++;
}
}
$sth->execute();

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

array data to mysql

I need to parse the following code and process the resulting data.
foreach($job as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
The above code is returning the following as expected.
Key=vca_id, Value=20130<br>Key=uuid, Value=3c87e0b3-cfa<br>Key=originate_time, Value=2013-03-15 14:30:18<br>
What I need to do is to put the values in mysql database. So the insert statement would look something like this...
insert into test.master_table (vca_id, uuid, originate_time) values ('20130', '3c87e0b3-cfa', '2013-03-15 14:30:18')
What is the correct way to save the array values to mysql database?
<?php
mysql_query("insert into test.master_table(vca_id, uuid, originate_time)values('".$job['vca_id']."','".$job['uuid']."','".$job['originate_time']."')");
?>
Well i will recommend implode
$keys = array();
$values = array();
foreach($job as $x => $x_value)
{
$keys[] = $x;
$values[] = $x_value;
}
$query = 'INSERT INTO test.master_table' . '('.implode(',',$keys) .') VALUES (' .implode(',',$values) . ')';
You can try this
$temp_value_arr = array();
$query = "INSERT into test.master_table SET ";
foreach($job as $x=>$x_value)
{
$query .= "$x = '$x_value',";
}
$query = rtrim($query, ',');
mysql_query($query);

Create table on master with data from slave in MySQL 5.1 and PHP 5.4

In MySQL 5.1 and PHP 5.4 I need to create temporary tables from the result of a query on a slave database. The problem is that I need the temporary table to be created on the Master (with data from the slave). It's the selection of the data for this table that carries all the overhead so I need the SELECT to happen on one of the slaves. The temporary table will be selected from for up to 2 hours, and I can't copy it to ALL the slaves (at least I don't think I can).
Here is what the code looks like:
$database->executeQuery ( "CREATE TABLE IF NOT EXISTS `" . $tableName . "` ENGINE = $engine CHARACTER SET utf8 ( " . $sql . ") " );
Again, the query in the $sql variable has to happen on the slave, while the table is created on the master.
Ok, turns out the way for me was to grab the result set in PHP from the slave, then create a SQL statement to insert it into the master.
public function createTemporaryTable ($tableName, $keyField = '', $sql = '', $engine = 'MEMORY') {
global $apdatabase;
$dbObj = new apdatabase();
$dbObj->setSqlCache(false);
$dbObj->setSqlBigResult(true);
$dbObj->setSqlCalcFoundRows(false);
$dbObj->setResultMode(MYSQLI_USE_RESULT);
$sql = $sql ? $sql : $this->getQuery();
$dbObj->executeQuery($sql);
$partsArr = array();
$foundRows = false;
$resultArr = $dbObj->getResultArray();
$dbObj->freeResultSet();
if (! count($resultArr)) {
return;
}
/*
* Set up the statement we will use to create the table definition
*/
$firstRow = $resultArr[0];
$fields = '';
$fieldDefinitionStr = '';
foreach ($firstRow as $field => $data) {
if ($fields != "") {
$fields .= ",";
$fieldDefinitionStr .= ",";
}
$fields .= $field;
$fieldDefinitionStr .= "`" . $field . "` VARCHAR (1024)";
}
parent::executeQuery("DROP TABLE IF EXISTS `" . $tableName . "`");
parent::executeQuery("CREATE TABLE `" . $tableName . "` ( " . $fieldDefinitionStr . ") ENGINE = $engine CHARACTER SET utf8");
/*
* Set up the sql to insert the remaining rows into our new table
*/
$sql = "INSERT IGNORE INTO `$tableName` ($fields) ";
$partsArr = array();
foreach ($resultArr as $row) {
$foundRows = true;
$rowSql = "(";
foreach ($row as $field) {
if ($rowSql != "(") {
$rowSql .= ",";
}
$rowSql .= "'" . $field . "'";
}
$rowSql .= ") ";
$partsArr[] = $rowSql;
}
parent::executeQuery($sql . "VALUES " . implode(', ', $partsArr));
if ($keyField) {
parent::executeQuery(" ALTER TABLE `" . $tableName . "` ADD KEY (`" . $keyField . "`) ");
}
}

SQL array values in php

Hi I'm really new to php/mysql.
I'm working on a php/mysql school project with 39 fields all in all in a single table.
I want to shorten my codes especially on doing sql queries.
$sql = "INSERT into mytable ('field_1',...'field_39') Values('{$_POST['textfield_1']}',...'{$_POST['textfield_39']}')";
I don't know how to figure out this but , i want something like:
$sql = "Insert into mytable ("----all fields generated via loop/array----") Values("----all form elements genrated via loop/array---")";
Thank you in advance.
<?php
function mysql_insert($table, $inserts) {
$values = array_map('mysql_real_escape_string', array_values($inserts));
$keys = array_keys($inserts);
return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>
For example:
<?php`enter code here`
mysql_insert('cars', array(
'make' => 'Aston Martin',
'model' => 'DB9',
'year' => '2009',
));
?>
try this it i thhink it il work
You could use implode:
$sql = "
INSERT into mytable
('" . implode("', '", array_keys($_POST) . "')
VALUES
('" . implode("', '", $_POST . "')";
(This assumes the indices of the POST array are also the names of the db table fields)
However, this is extremely insecure since you would directly insert post data into the database.
So the least you should do beforehand is escape the values and make sure they are ok/valid table fields:
// Apply mysql_real_escape_string to every POST value
array_walk($_POST, "mysql_real_escape_string");
and
// Filter out all POST values with invalid indices
$allowed_fields = array('field_1', 'field_2', /* ... */ );
$_POST = array_intersect_key($_POST, $allowed_fields);
<?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "'" . $_POST[textfield_$i] . "'";
} else {
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
?>
< ?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
if(is_int($POST[textfield$i])){
$sql .= $POST[textfield$i];
}
else{
$sql .= "'" . $POST[textfield$i] . "'";
}
} else {
if(is_int($_POST[textfield_$i])){
$sql .= $_POST[textfield_$i] .",";
}
else{
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
}
?>
it will work for numeric values. you can insert numeric values in single quotes but some times it will create some problems

Categories