How to insert this data to mysql php - php

Array
(
[id] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
[kind] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[qty] => Array
(
[0] => 123
[1] => 456
[2] => 789
)
)
This is how my data look like.Here is my insert 1 row code
function insert($table, $array_data)
{
$key = array();
$value = array();
foreach($array_data as $v=>$row){
$key[] = $v;
$value[] = "'".$row."'";
}
$data_key = implode(',', $key);
$data_value = implode(',', $value);
$sql = "INSERT INTO ".$table."(".$data_key.") VALUES (".$data_value.")";
$this->setQuery($sql);
$this->query();
}
Please help me make a function to insert multi rows somethings like
function insert_multi($table, $array_data)
{
...
$sql = "INSERT INTO ".$table."(".$data_key.") VALUES (".$data_value1."), (".$data_value2.")";
$this->setQuery($sql);
$this->query();
}
I'm trying many ways but only return empty value or "Array" string. My point is make those value turn into this
INSERT INTO table (id, kind, qty) VALUES (1, v2, v3), (1, v2.1, v3.1),...
Many thanks! ^^

Guess you want something like this:
function insert_multi($table, $array_data)
{
$sql = "INSERT INTO " . $table . " (" . implode(',', array_keys($array_data)) . ") VALUES ";
$rows = [];
$columns = array_keys($array_data);
for ($ii = 0; $ii < count($array_data[$columns[0]]); $ii++) {
$values = [];
foreach ($columns as $column) {
$values [] = $array_data[$column][$ii];
}
$rows [] = "('" . implode("','", $values) . "')";
}
$sql .= implode(',', $rows);
$this->setQuery($sql);
$this->query();
}
but brace yourself for SQL injections when building queries that way...

Hope this will help you. Not tested so make changes if there is any syntax error.
you need to just generate a string like (val1,val2),(val3,val3)
function them($table, $array_data)
{
...
$keys = array_keys($array_data);
$length = count($array_data[$keys[0]]);
$sql = '';
for ($i=0;$i < $length;$i++)
{
$sql .= "('";
foreach($keys as $index => $key){
$sql .= $array_data[$key][$i];
if($index < count($keys)-1)
$sql .= ",";
}
$sql .= "')";
// if there is another array member, add a comma
if( $i < $length-1 )
{
$sql .= ",";
}
}
$sql = "INSERT INTO ".$table."(".implode(',',$keys).") VALUES ".$sql;
$this->setQuery($sql);
$this->query();
}

Related

removing last comma from string rtrim

Can't seem to get rtrim to work and I don't understand why:
$array = array("top" => array("one" => "inner one", "two" => "inner two"));
foreach (array_keys($array) as $key) {
$form[$key] = array();
$sql = "INSERT INTO $key SET ";
foreach (array_keys($array[$key]) as $field) {
array_push($form[$key], $field);
$sql .= $field." = '".$array[$key][$field]."',";
}
}
rtrim($sql,',');
$sql .= ";";
Why would this not get rid of the last comma?
it keeps printing out this:
INSERT INTO top SET one = 'inner one',two = 'inner two',;
You have to assign the rtrim to $sql like that:
$sql = trim($sql, ",");
Better way is to use implode(). Example:
$array = array("top" => array("one" => "inner one", "two" => "inner two"));
foreach($array as $key=>$val){
$form = array();
$sql = "INSERT INTO $key SET ";
foreach ($val as $k=>$field) {
array_push($form, $k."='".$field."'");
}
$sql .= implode(",",$form);
//echo $sql;
}
Output:
INSERT INTO top SET one='inner one',two='inner two'
You forgot to overwrite $sql variable with rtrim result
$array = array("top" => array("one" => "inner one", "two" => "inner two"));
foreach (array_keys($array) as $key) {
$form[$key] = array();
$sql = "INSERT INTO $key SET ";
foreach (array_keys($array[$key]) as $field) {
array_push($form[$key], $field);
$sql .= $field." = '".$array[$key][$field]."',";
}
}
$sql = rtrim($sql,',');
$sql .= ";";

Number not getting added in mysql database format ( number - number )

I need to add data in my database and one way or the other the format must be like,
0 - 0 or 1 - 5
i have tryed =>
mysqli_real_escape_string();
but did not work.
i have also tryed changing the sign to / , * , +, exp.
PHP
$dataBase->_insertDataBase('tableNaam', $input);
function _insertDataBase($tabel,$input){
$velden='';
$waarden='';
$i=0;
foreach($input AS $key=>$value){
$i=$i+1;
if($i !== count($input)){
$a=', ';
}else{
$a='';
}
$velden.=$key.$a;
$waarden.=$value.$a;
unset($a);
}
$sql = "INSERT INTO `$tabel`($velden) VALUES ($waarden)";
$this->_conn()->query($sql);
}
The problem is your SQL statement is giving the equation 5-1 as a value, so the server is doing the math and inserting 4 just like you told it to. You need tell it that it's a literal string by surrounding the values with apostrophe's (i.e. '5-1').
Replace:
foreach ($input AS $key => $value) {
$i = $i + 1;
if ($i !== count($input)) {
$a = ', ';
} else {
$a = '';
}
$velden .= $key . $a;
$waarden .= $value . $a;
unset($a);
}
With:
$velden = array();
$waarden = array();
foreach ($input AS $key => $value) {
$velden[] = $key;
$waarden[] = $value;
}
$velden = implode(',', $velden);
$waarden = "'" . implode("','", $waarden) . "'";
Or possibly even:
$velden = array_keys($input);
$waarden = array_values($input);
$velden = implode(',', $velden);
$waarden = "'" . implode("','", $waarden) . "'";

php mysql insert value from an array

I have an array.Now I want to insert data in my table using this array value.
$claw is the array
Array
(
[0] => Array
(
[0] => Alabama
[1] => Yes
[2] => R
[3] =>
are free to enact restrictions greater than .
[4] =>
[5] =>
[6] =>
[7] =>
It is unlawful to sell
)
)
Now I want to insert data in my table using this array value.
I am using this code but not work
public function Insert($claw)
{
$fields = array();
for($i=0;$i<$claw; $i++)
{
for($j=0;$j<$claw[$i]; $j++)
{
$fields[] = $claw[$i][$j];
}
}
$sql = "Insert into information values(" . implode(', ', $fields) . ')';
return $this->MyCommandR($sql);
}
I cant understand whats my wrong
You need to define the field to save these data
$sql = "Insert into information (name,yes,ABC,CBA) values(" . implode(', ', $fields) . ')';
or
$field = $conn->query("DESCRIBE `".$table."`");
$constrantsQueryfield = array();
$constrantsQueryvalue = array();
while($row = mysqli_fetch_assoc($field))
{
if ($row['Field']!='ID' && $row['Key']!='PRI')
{
if (array_key_exists($row['Field'],$data))
{
if ($row['Key']=='DATE')
{
$constrantsQueryfield[] = $row['Field'];
$constrantsQueryvalue[] = date("Y-m-d");
}
else
{
$constrantsQueryfield[] = $row['Field'];
$constrantsQueryvalue[] = $data[$row['Field']];
}
}
}
}
$constrantQuery = "INSERT INTO `".$table."` ";
for ($i = 0;$i<count($constrantsQueryfield);$i++)
{
if ($i == 0){
$constrantQuery .= "(";
}
$constrantQuery .= "`".$constrantsQueryfield[$i]."`";
if ($i+1 == count($constrantsQueryfield))
{
$constrantQuery .= ")";
}
else
{
$constrantQuery .= ", ";
}
}
$constrantQuery .= " VALUES ";
$contstantQuery .= "(" . implode(', ', $data) . ')'; // ANy data array
$conn->query($constrantQuery);

PHP Dynamically create SQL query with AND condition

I am trying to write some PHP that fits in to a larger method so that I can dynamically create a MySQL query.
I haven't included the code to the larger method that contains this code because I think the logic of this bit is self-contained.
So, I have a multi-dimensional array:
$where=array(array('username', 'pid', 'name'), array('=','<=', '='), array('alex',2,'james'));
which when I print_r() shows this structure:
Array
(
[0] => Array
(
[0] => username
[1] => pid
[2] => name
)
[1] => Array
(
[0] => =
[1] => <=
[2] => =
)
[2] => Array
(
[0] => alex
[1] => 2
[2] => james
)
)
What I would like to do if use the first value in each second level array to build up the start of the query such as
SELECT * FROM table WHERE username = alex
and then use the other values to build up the query such as (depending upon the number of items in the arrays)
SELECT * FROM table WHERE username = alex AND pid <= 2 AND name = james
Below is the code I have written
if (is_array($where[0])){
$i=0;
$field = $where[0][$i];
$operator = $where[1][$i];
$value= $where[2][$i];
$sql= "SELECT * FROM table WHERE {$field} {$operator} {$value}";
while($i=0 ) {
print $sql;
$i++;
}
while($i>0 AND $i< sizeof($where[0]))
$field = $where[0][$i];
$operator = $where[1][$i];
$value= $where[2][$i];
print $sql .= " AND {$field} {$operator} {$value}";
$i++;
}
However this prints out just one query
SELECT * FROM table WHERE username = alex AND username = alex
I am using PDO so in reality {$value} is replaced by ? and bound elsewhere in the method. I've just shown it here in full.
$sql = 'SELECT * FROM table WHERE';
for($i = 0; $i < count($where[0]); $i++){
$sql .= " {$where[0][$i]} {$where[1][$i]} {$where[2][$i]} AND";
}
$sql = substr($sql, 0, strlen($sql) - 4);
I personally would however save your statements like this:
$array = array('username = alex', 'pid <= 2');
If you needed the different parts of the statements, you could just do
explode(' ', $array[num]);
$companyFilter = "";
$auth = getFormulaAuth();
$companyFilter = "AND company_id = {$auth['company_id']} ";
$arguments = func_get_args();
if ($WhereFilterName_xxx) {
} else {
$db = new Database();
$this_get_table_form = getFormulaFormDetails($FormName);
$tbfields_data = Formula::getTBFields($this_get_table_form["id"], $db);
$q_string = "SELECT * FROM `" . $this_get_table_form["form_table_name"] . "`";
$valid_param_check = count($arguments) - 2;
$cache_key = "*";
if ($valid_param_check >= 1 && $valid_param_check % 3 == 0) {
$found_indexes = array();
$q_string_where = " WHERE ";
$search = " (NOT EXISTS(SELECT * FROM tbtrash_bin WHERE record_id = " . $this_get_table_form["form_table_name"] . ".id
AND form_id = " . $this_get_table_form["id"] . "
AND table_name='" . $this_get_table_form["form_table_name"] . "')) AND ";
$q_string_where .= $search;
for ($i = 2; $i < count($arguments); $i+=3) {
$field_key = $arguments[$i];
$operator = $arguments[$i + 1];
$value = $arguments[$i + 2];
if ($i > 2) {
$q_string_where .= " AND ";
}
$q_string_where .= " `" . $field_key . "` " . $operator;
if (($tbfields_data["" . $field_key]["field_input_type"] == "Number" || $tbfields_data["" . $field_key]["field_input_type"] == "Currency") || strtoupper($operator) == "IN") {
$q_string_where .= " " . $value . " ";
} else {
$q_string_where .= " '" . $value . "' ";
}
$q_string_orderby .= $q_string_where;
$sort_by = isset($_GET['s']) ? $_GET['s'] : false;
switch ($sort_by) {
case $tbfields_data;
break;
default:
$sort_by = 'DateCreated';
}
$q_string_orderby .= ' ORDER BY '.$sort_by.' ';
$direction = isset($_GET['d']) ? $_GET['d'] : false;
if ($direction != 'ASC' && $direction != 'DESC')
$direction = 'DESC';
$q_string_orderby .= $direction;
$res = $db->query($q_string_orderby);
$results = array();
if ($res) {
while ($r = mysql_fetch_assoc($res)) {
$results[] = $r;
}
}
$cache_key.="::" . $field_key . "::" . $operator . "::" . $value . "::" . $q_string_orderby;
}
$q_string .= $q_string_orderby;
}
$this_record = Formula::getLookupValue("formula_lookup_where_array", $this_get_table_form, $q_string, $cache_key);
array_push($GLOBALS['formula_executed_data_collector']['collected_form_id'], array(
"form_id" => $this_get_table_form['id'],
"where" => $q_string_where,
"function_name" => "Total",
"whole_query" => $q_string
));
$rslt = array_values(array_map(function($a) use($ReturnField) {
if (gettype($ReturnField) == "array") {
$array_collector = array();
foreach ($ReturnField as $key => $value) {
$array_collector[$value] = $a[$value];
}
return $array_collector;
} else if ($ReturnField == "*") {
return $a;
} else {
return $a[$ReturnField];
}
}, $this_record));
return $rslt;
}
}

Read Excel file in array or get adyacent columns values with PHPExcel

I have a Excel file with content like the showed in the image:
As you may see there is basically three columns (could be four or more) which represents categories and subcategories. I need to read this Excel file for then write some SQL sentences like for example:
INSERT INTO `category` (name, parent, status, modified) VALUES('Electronica', NULL, 1, NOW());
INSERT INTO `category` (name, parent, status, modified) VALUES('Celulares y Telefonos', 1, 1, NOW());
INSERT INTO `category` (name, parent, status, modified) VALUES('Accesorios para celulares', 2, 1, NOW());
I know how to read the file using PHPExcel_IO but don't know how to get the parent > childrens relationship in order to build the proper SQL sentences, any help or advice?
UPDATE
This is what I have done so far. First here is the complete source if yours have any problems please feel free to contact me in order to send the file (I do this because the Array is to large and services like pastie.org doesn't allow to publish it and here will ugly the post).
I created this function to read the array data:
function print_r_reverse($in) {
$lines = explode("\n", trim($in));
if (trim($lines[0]) != 'Array') {
return $in;
} else {
if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
$spaces = $match[1];
$spaces_length = strlen($spaces);
$lines_total = count($lines);
for ($i = 0; $i < $lines_total; $i++) {
if (substr($lines[$i], 0, $spaces_length) == $spaces) {
$lines[$i] = substr($lines[$i], $spaces_length);
}
}
}
array_shift($lines); // Array
array_shift($lines); // (
array_pop($lines); // )
$in = implode("\n", $lines);
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
$pos = array();
$previous_key = '';
$in_length = strlen($in);
foreach ($matches as $match) {
$key = $match[1][0];
$start = $match[0][1] + strlen($match[0][0]);
$pos[$key] = array($start, $in_length);
if ($previous_key != '')
$pos[$previous_key][1] = $match[0][1] - 1;
$previous_key = $key;
}
$ret = array();
foreach ($pos as $key => $where) {
$ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
}
return $ret;
}
}
And this is the code I have created to read the array values and write the SQL sentences:
$result = print_r_reverse($arrayData);
class RPMQGen {
var $array_to = "";
var $count = 1;
var $last_count_parent = -1;
var $t_name = "";
function RPMQGen($tableName, $array) {
$this->t_name = $tableName;
$this->array_to = $array;
}
function walk_children($value) {
$query = "";
$key_result = 0;
$index_count = 0;
foreach ($value as $key => $val)
if (strlen($val) > 1) {
$index_count++;
$key_result = $key;
};
if ($index_count > 1) {
foreach ($value as $key => $val) {
if (strlen($val) > 1) {
$query = $query . "INSERT INTO `" . $this->t_name . "` (`id`, `name`, `parent`, `deletedAt`) VALUES (" . $this->count . ",`" . $val . "`, " . ($key + 1) . ", 1, NULL); <br>";
$this->count++;
}
}
$this->last_count_parent = $this->count;
} else
if ($index_count == 1) {
$query = $query . "INSERT INTO `" . $this->t_name . "` (`id`, `name`, `parent`, `deletedAt`) VALUES (" . $this->count . ",`" . ($value[$key_result]) . "`, " . ($this->last_count_parent - 1) . ", 1, NULL); <br>";
$this->count++;
}
return $query;
}
function get_queries() {
$this->count = 2;
$query = "INSERT INTO `" . $this->t_name . "` (`id`, `name`, `parent`, `deletedAt`) VALUES (1,`root`, NULL, NULL); <br>";
foreach ($this->array_to as $key => $value) {
$query = $query . "INSERT INTO `" . $this->t_name . "` (`id`, `name`, `parent`, `deletedAt`) VALUES (" . $this->count . ",`" . $key . "`, 0, NULL); <br>";
$this->count++;
foreach ($value as $key => $value2) {
$query = $query . $this->walk_children($value2);
}
}
print($query);
}
}
$qgen = new RPMQGen('category', $result);
$qgen->get_queries();
But parent > children relations aren't right and I can't find the cause
Make 4 loops, one for each column. If the value is not empty, it means that the product is part of that column category. Not that hard really.

Categories