how to delete id from MySQL Database using query - php

I am trying to delete Id on SQL not working i got string(87) "DELETE FROM wp_availability WHEREidIN (Array,Array,Array,Array)"
get this kind value
if ( count( $remove ) > 0 ) {
$removeSQL = "DELETE FROM " . $this->table . " WHERE `id` IN (" .
implode( ",", $remove ) . ")";
if ( $wpdb->query( $removeSQL ) ) {
$saved = true;
}
}
Thanks in Advance

To expand on Vince0789's answer...
$remove looks to contain an array of arrays and not just an id string.
For example, $remove may be layed out as below;
[
[
'id' => 1,
'content' => "Foo"
],
[
'id' => 2,
'content' => "Bar"
],
]
What you will want to do is use array_column() on the $remove array to capture just the IDs from the array and then implode that new array and pass it to the query.
$to_remove = array_column($remove, 'id'); //assuming that id is the column you want
http://php.net/manual/en/function.array-column.php

Related

Insert array into a single field in a MYSQL database

I am creating a SELECT drown down list, I would like to have it loaded in 1 of 2 ways.
First way is pulling data from database with ID, name, and Value - This way will be loaded from other pages.
Second way, I would like to load from a Single line in the database with Name and Value. But I want to have that value be loaded with an array.
How do I load that array into the database?
$name = 'name';
$value = array( 'red' => 'Red', 'blue' => 'Blue' );
$SQL = 'INSERT INTO table_name (name, value) VALUES ($name,$value);
I expect when I run the SELECT * from table_name WHERE name = "name" to use that array in the value field right away.
With what "RakeshJakhar" said, to use the implode and explode onto $value
$value = array( 'red' => 'Red', 'blue' => 'Blue' );
print_r( $value );
echo "<br />";
echo implode( ",", $value );
echo "<br />";
$implode = implode( ",", $value );
$explode = explode( ',', $implode );
print_r( $explode );
Results:
Array ( [red] => Red [blue] => Blue )
Red,Blue
Array ( [0] => Red [1] => Blue )
You can use json_encode and json_decode
$value = array( 'red' => 'Red', 'blue' => 'Blue' );
$column = json_encode($value);
So the inserted value {"red":"Red","blue":"Blue"}
When you are fetching value use json_decode
$values = json_decode($column,true);

Parse php array to make insert statement

Hi I have an array like this:
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
]
foreach($datas as $data){
//get items here...
}
How to pair or parse those items to make insert statement like this:
INSERT INTO table (name, settings)VALUES('John','Settings 1');
INSERT INTO table (name, settings)VALUES('Mickey','Settings 2');
Any idea? Thanks in advance.
This code could be usefull for creating array of arrays. Considering array keys will be name_x and settings_x
foreach($datas as $key=>$value){
// explode each key of the array
$keys = explode('_',$key);
$name = 'name_'.$keys[1];
$settings = 'settings_'.$keys[1];
// to generate array
$new_array[$keys[1]]=array('name'=>$datas[$name], 'settings'=>$datas[$settings]);
}
print_r($new_array);
Loop the $new_array for insert query.
Output :
Array
(
[1] => Array
(
[name] => John
[settings] => Settings 1
)
[2] => Array
(
[name] => Mickey
[settings] => Settings 2
)
)
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
];
$results = [];
foreach($datas as $index=>$data){
//create an array out of $index breaking it at the '_'
//so array will be $parts = [0=>'name', 1=>'1'];
$parts = explode('_', $index);
//'name_1'=>'John' = $results[1]['name'] = 'John';
$results[$parts[1]][$parts[0]] = $data;
}
//batch insert new formed array
//INSERT INTO tbl_name (name, settings) VALUES $results;
Check this, you must do some intermediate steps. Comments on code!!
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
];
$data_final = [];
foreach($datas as $key=>$value){
$keyX = preg_replace('/^(.+)_(\d+)$/', '$1', $key);// get the "type" (name, setting)
$keyY = preg_replace('/^(.+)_(\d+)$/', '$2', $key);// get the "index" (_1, _2 without "_")
$data_final[$keyY][$keyX] = $value; // put in result
}
// make queries
$sql = [];
foreach($data_final as $datas){
$fields = implode(", ", array_keys($datas)); //implode the keys to sql fields
$values = implode(", ", array_map(function($a){return "'$a'";}, array_values($datas)));//implode values to sql values adding ''. WARNING: This not escape values. Use escape string function on mysqli obj or PDO to the right escape
$sql[] = "INSERT INTO table ($fields) VALUES ($values);"; // populate query
}
$sql = implode("\n", $sql); // implode with new line
print_r($sql); //results
IMPORTANT:
You must have the right syntax "field_number" to respect the procedure
You can use even with one or more of two fields per record
You can use any field name, always respecting the "field_number" syntax
DEMO HERE

PHP - array key within array value

I have a PHP array like this:
$arr = array(
'id' => 'app.settings.value.id',
'title' => 'app.settings.value.title',
'user' => 'app.settings.value.user'
);
I want to remove '.id', '.title' and '.user' in the array values. I want to insert the key of this array at the end of the value. I know, that I can get an array key by passing an array and a value to 'array_search', but I want the key within this one array definition - at the end of it's value. Is this possible?
I don't like this, but I guess it's simple and works:
$arr = array(
'id' => 'app.settings.value',
'title' => 'app.settings.value',
'user' => 'app.settings.value'
);
$result = array();
foreach ($arr AS $key => $value) {
$result[$key] = $value . '.' . $key;
}
You're storing app.settings.value which is the same for all array items, so personally I'd prefer:
$arr = array(
'id',
'title',
'user'
);
function prepend_key($key)
{
return 'app.settings.value.' . $key;
}
$result = array_map('prepend_key', $arr);
With $result containing:
array(
'app.settings.value.id',
'app.settings.value.title',
'app.settings.value.user'
);
At the end of the day, either works :)

Using an array value to retrieve from another array

I have created an array, one of the is intended to be a string used by php to display a field from a record retrieved from sqlite3.
My problem is that ... it doesn't.
The array is defined, "1" being the first database field, and "2" is the second database field:
EDIT : I have re-defined the problem as a script so you can see the whole thing:
//If I have an array (simulating a record retrieved from database):
$record = array(
name => 'Joe',
comments => 'Good Bloke',
);
//then I define an array to reference it:
$fields = array(
1 => array(
'db_index' => 'name',
'db_type' => 'TEXT',
'display' => '$record["name"]',
'form_label' => 'Name',
),
2 => array(
'db_index' => 'comments',
'db_type' => 'TEXT',
'display' => '$record["comments"]',
'form_label' => 'Comments',
),
);
//If I use the lines:
print "expected output:\n";
print " Name = " . $record["name"] ."\n";
print " Comments = " . $record["comments"] ."\n";
//I display the results from the $record array correctly.
//However if I try & use the fields array with something like:
Print "Output using Array values\n";
foreach($GLOBALS["fields"] as $field)
{
$label = $field['form_label'];
$it = $field['display'];
$line = "\"$label = \" . $it .\"\n\"";
print $line;
}
Output:
Expected output:
Name = Joe
Comments = Good Bloke
Output using Array values:
Name = $record["name"]
Comments = $record["comments"]
Don't call variable from string. Just concatenate it :
foreach($GLOBALS["fields"] as $field){
$label = $field['form_label'];
$it = $field['display'];
eval("$it = ".$it);
$line = $label." = ".$it."\n";
print $line;
}
Well, how do it looks ?

Create Array from Mysql data for Flot

I have a problem in that I can't get an array into an array.
The outcome should look like this:
$data=array(
array(
'label' => 'Totals',
'color' => '#745fa4',
'data' =>
array(
array('01/01/2015', 125),
array('02/01/2015', 148),
array('03/01/2015', 42),
array('04/01/2015', 115),
array('05/01/2015', 45),
array('06/01/2015', 77),
array('07/01/2015', 59)
)
),
);
I currently have this but can't get it into the correct format:
$result = mysqli_query($con,"SELECT * FROM table ORDER BY id DESC LIMIT 28");
$chartdata = array();
while($row = $result->fetch_assoc()) {
$chartdata[] .= array($row["date"]. ", " . $row["total"]);
}
$data=array(
array(
'label' => 'Totals',
'color' => '#745fa4',
'data' => $chartdata
)
);
If someone could help me out that would be fantastic.
1) .= this means assignment with string concatenation. you should push array into parent array
2) inside child array have two values not single string so use , between two value not string concatenation ","
$chartdata[] .= array($row["date"]. ", " . $row["total"]);
to
$chartdata[] = array($row["date"], $row["total"]);
You have a superfluous dot here:
# ⇓
$chartdata[] .= array($row["date"]. ", " . $row["total"]);
To push new item into an array one should use $array[] = $item:
$chartdata[] = array($row["date"]. ", " . $row["total"]);
Dot is used to concatenate strings. Hope it helps.
Remove the dot.
<?php
$result = mysqli_query($con,"SELECT * FROM table ORDER BY id DESC LIMIT 28");
$chartdata = array();
while($row = $result->fetch_assoc()) {
$chartdata[] = array($row["date"], $row["total"]); // Remove the dot
}
$data=array(
array(
'label' => 'Totals',
'color' => '#745fa4',
'data' => $chartdata
)
);

Categories