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);
Related
I have a function to calculate distance, the data comes from a database.
Here is the code for calculating:
function jarak() {
global $conn;
$query1 = mysqli_query($conn, "SELECT signature, sig_priority FROM centro");
$query2 = mysqli_query($conn, "SELECT signature, sig_priority, status FROM acid_event");
while ($row = mysqli_fetch_array($query1, MYSQLI_ASSOC)) { $master[]=$row; }
while ($row = mysqli_fetch_array($query2, MYSQLI_ASSOC)) { $data[]=$row; }
$jarak = array();
foreach ($data as $key => $val) {
foreach ($master as $key2 => $value) {
$jarak = sprintf("%0.2f",sqrt(pow($val['signature'] - $value['signature'], 2) + pow($val['sig_priority'] - $value['sig_priority'], 2)));
echo "distance from (" . $value['signature'] . "," . $value['sig_priority'] . ") ke (" . $val['signature'] . "," . $val['sig_priority'] . ") is : " . $jarak . "<br>";
$euc[]=$jarak;
}
}
}
And here is the result from that:
Array(
[0] => 30.04
[1] => 0.00
[2] => 30.04
[3] => 0.00
[4] => 47.00
[5] => 17.03
[6] => 5.02
[7] => 25.08
[8] => 2.06
[9] => 32.06
[10] => 37.00
[11] => 7.07 )
I want to compare each 2 index array with greater than or less than.
Example : [0] with [1], [2] with [3], [4] with [5] and so on. It just compare with 2 index.
I tried this but no result
for ($i=0; $i<count($cb); $i++) {
for ($k=0;$k<2;$k++) {
if($cb[$i][$k]<$cb[$i][$k]) {
echo "low";
} elseif ($cb[$i][$k]>$cb[$i][$k]) {
echo "high";
}
}
}
Output I want should look like this
if [0] < [1] then "high" and it loop for other index array like [2] with [3], [4] with [5] and so on.
I think you were quite close to what you wanted to accomplish but it seems like you were making things harder than they needed to be.
Your code is below.
for ($i=0; $i<count($cb); $i++) {
for ($k=0;$k<2;$k++) {
if($cb[$i][$k]<$cb[$i][$k]) {
echo "low";
} elseif ($cb[$i][$k]>$cb[$i][$k]) {
echo "high";
}
}
}
As you can see your if statements are comparing the exact same value to each other, that's not going to do much. But I can see what you were trying to do in the second for loop.
Instead, what we really want to do is move through your array in steps of 2.
for ($i=0; $i<count($cb); $i+=2) {
//stuff
}
This way we can compare the first element and the element after that to each other. Like this:
if($cb[$i] > $cb[$i+1]) {
echo $i . 'is higher than '. $i+1;
} elseif($cb[$i] < $cb[$i+1]) {
echo $i . 'is lower than '. $i+1;
} else {
echo $i . 'is the same as '. $i+1;
}
So all together it would be something like this:
for ($i=0; $i<count($cb); $i+=2) {
if($cb[$i] > $cb[$i+1]) {
echo $i . 'is higher than '. $i+1;
} elseif($cb[$i] < $cb[$i+1]) {
echo $i . 'is lower than '. $i+1;
} else {
echo $i . 'is the same as '. $i+1;
}
}
Now you can change the echo's to whatever you want to do and you should probably add some validation too (like checking if the keys actually exist before accessing them), but this is a good place to get started.
I did a solution, but I decided to keep the response in an array because it makes more sense to me to be able to read this information somewhere else later.
Here's my solution:
$test = array(
30.04,
0.00,
30.04,
0.00,
47.00,
17.03,
5.02,
25.08,
2.06,
32.06,
37.00,
7.07,
);
$output = array();
foreach ($test as $key => $value) {
// To make sure this will only be executed every second item
if ($key % 2 !== 0) {
continue;
}
$next = '';
if (!isset($test[$key+1])) {
break;
} else {
$next = $test[$key+1];
}
$output[$key] = $value . ' is ' . ($value < $next
? "lower"
: ($value > $next
? 'higher'
: 'equal')) . ' than ' . $next;
}
echo '<pre>';
print_r($output);
Here's the code tested: https://3v4l.org/Pg5La
I am trying to build a search query based on the input from users, but I am having problems with the AND and WHERE keywords. Here is the code:
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array();
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
$where[] = $key . ' = ' . $value;
}
}
}
The output looks like this:
Array
(
[0] => gender = masculine
[1] => level = low
[2] => status = future
)
If no option is selected, it defaults to 'all' and it is excluded from the $where[].
I need to achieve this, or anything similar:
Array
(
[0] => WHERE gender = masculine
[1] => AND level = low
[2] => AND status = future
)
The WHERE must be appended only if one or more options have been selected and the AND must be appended only if two or more options have been selected.
In the code I am using I have 9 search inputs. To keep it clear I only displayed three in the snippet. Can you please help me figure this out?
Try this:I think you need the whereClause in string not in array,here you can choose any one from two and remove the other one.
<?php
$where=array();$flag=0;// use flag to identify the where/and
$whereClause="";
$criteria = array('gender' => "masculine", 'level' => "low", 'status' => "future");
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($flag == 0){
$where[] = " WHERE " .$key . ' = ' . $value;//if you need array
$whereClause='WHERE '.$key . ' = "' . $value.'"';//if you need string
}else{
$where[] = " AND " .$key . ' = ' . $value;
$whereClause .=' AND '.$key . ' = "' . $value.'"';
}
$flag++;
}
}
echo "<pre>";
print_r($where);
echo "</pre>";
echo $whereClause;
?>
You can do this :
$query = 'SELECT * FROM candidate ';
$where='';
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($where=='')
$where='WHERE '.$key . ' = ' . $value;
else
$where.=' AND '.$key . ' = ' . $value;
}
}
$query.=$where; //final query
You can use simple switch statement too
<?
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array();
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value)
{
if ($value !== 'all')
{
switch ($key)
{
case 1:
{
$query = " WHERE " .$key . ' = ' . $value;
break;
}
case 2:
{
$query = " AND " .$key . ' = ' . $value;
break;
}
case 3:
{
$query = " AND " .$key . ' = ' . $value;
break;
}
}
$where[] = $query;
}
}
}
You need to put one incrementer ($inc) and then put the conditions as:
$inc=1;
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($inc==1){
$where[] = 'Where '.$key . ' = ' . $value.'';
}else{
$where[] = 'AND '.$key . ' = ' . $value.'';
}
$inc++;
}
}
In My view there is one more clean way of achiving this:
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array("Where 1=1");
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
$where[] = 'AND '.$key . ' = ' . $value.' ';
}
}
}
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();
}
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;
}
}
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.