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 .= ";";
Related
public function update($id, $table, $data, $exclude = array()){
$query = "UPDATE $table SET";
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
$fields = implode(" ", $fields);
$values = implode(" ", $values);
$query .= $fields . "=" . $values . ",";
}
$query = $query . "WHERE id = '".$id."' ";
if(!$this->db->query($query)){
echo "Something wrong with query ";
}
else{
echo "successfully updated";
}
}
Got error
Fatal error: [] operator not supported for strings
Tweaked code from add function which worked. Wanted to have fields and values updated dynamically without using variables, i.e. $_POST['address'].
$query .= $fields . "=" . $values . ", ";
seem not to be working. Not sure what cause the error: Fatal error: [] operator not supported for strings. How to insert field = value in sql query?
Use like this
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$query .= $key . "='" . $data[$key] . "' ,";
}
}
$query = substr($query,0,strlen($query)-1);
$query = $query . " WHERE id = '".$id."' ";
Look at the foreach loop!!!
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
$fields = implode(" ", $fields); // Mistake done here
$values = implode(" ", $values); // Mistake done here
$query .= $fields . "=" . $values . ",";
}
Change your those two line and the next line outside the loop. May be this solve your problem.
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
}
$fields = implode(" ", $fields);
$values = implode(" ", $values);
$query .= $fields . "=" . $values . ",";
Follow my code. Where no need implementation implode() function. I have changed your function code. try it.
public function update($id, $table, $data, $exclude = array()){
$query = "UPDATE $table SET";
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$queryArr[] = $key . "='" . $this->db->real_escape_string($data[$key]);
}
}
$query = implode(" ,", $queryArr);
$query = $query . "WHERE id = '".$id."' ";
if(!$this->db->query($query)){
echo "Something wrong with query ";
}
else{
echo "successfully updated";
}
}
How can i remove "dato" from $this->v ? And still have it in the $sql string.
OUTPUT (var_dump($this->v)):
array (size=4)
':kategori' => string 'Youstube' (length=8)
':link' => string 'http://urls' (length=11)
':navn' => string 'Rss feeds' (length=9)
':dato' => string 'NOW()' (length=5)
OUTPUT (echo $sql)
UPDATE rss_kategori SET kategori = :kategori, link = :link, navn = :navn, dato = NOW()
CODE:
$classVars = get_class_vars(get_class($this));
$sql .= "UPDATE {$this->table} SET ";
foreach ($classVars as $key => $value) {
if ($key == 'v' || $key == 'db' || $key == 'id' || $key == 'table' || $key ==
'table_id') {
continue;
}
$keys = "";
$values = "";
$keys .= $key;
if ($this->$key == 'NOW()') {
$values .= $this->$key . ",";
} else {
$values .= ":" . $key . ",";
}
$this->v[":" . $key] = $this->$key;
$sql .= "{$keys} = " . $values . " ";
}
$sql = substr($sql, 0, -2) . " WHERE {$this->table_id} = '{$this->id}'";
Please try this:
$key = ':dato';
$arr = $this->v;
if (array_key_exists($key, $this->v) {
unset($arr[$key]);
$this->v = $arr;
}
Try using unset() function.
unset($this->v['dato']);
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 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) . "'";
Trying to loop through a querystring in php but only getting last value. What should I be doing to get all values?
example:
querystring = ?style=ranch&style=barn&style=colonial
php:
$sqlStyle = "SELECT DISTINCT COUNT(*) as count FROM houses_single ";
$i = 1;
foreach ($_GET as $key => $value) {
if ($i == 1){
$sqlStyle .= "where ";
}else{
$sqlStyle .= " and ";
}
$sqlStyle .= $key . " like '%" . $value ."%'";
$i++;
}
echo $sqlStyle;
Result:
SELECT DISTINCT COUNT(*) as count FROM houses_single Where Houses like '%colonial%'
The query parameter "style" is an array in this case and must be identified by square brackets - if not, the last key=value pair will overwrite the others.
?style[]=ranch&style[]=barn&style[]=colonial
$_GET['style'] is an array then you can loop over by using foreach:
foreach ($_GET['style'] as $value) {
// ...
}
if 'style' is not the only parameter you want to add, you can use a is_array() check in the foreach loop:
foreach ($_GET as $key => $value) {
if ($i == 1){
$sqlStyle .= "where ";
}else{
$sqlStyle .= " and ";
}
if(is_array($value)) {
$sec = array();
foreach($value as $second_level) {
$sec[] = $key . " LIKE '%" . $second_level."%'";
}
$sqlStyle .= implode(' AND ', $sec);
}
else {
$sqlStyle .= $key . " LIKE '%" . $value ."%'";
}
$i++;
}
echo $sqlStyle;
alternative without foreach:
<?php
$statement = "SELECT DISTINCT COUNT(*) as count FROM `houses_single`";
if(is_array($_GET)) {
$statement .= ' WHERE';
// create copy to keep the $_GET array
$add_where = $_GET;
array_walk(function($elem,$key){
is_array($elem) {
return implode(' AND ', array_map(function($sec) using ($key) {
return "$key LIKE '%$sec%'";
}, $elem);
}
else {
return "$key LIKE '%$elem%'";
}
},$add_where);
$statement .= implode(' AND ', $add_where);
}
(codes are untested)
Sidenode about safety: I hope you won't use this code snippet you provided in productive environment without any escaping of the parameters.