How to insert an array into a Mysql table - php

I want to insert an array ($array) into a Mysql table (notification), I tried this but nothing is entering. How do I solve this?
$select = "SELECT * FROM addclique WHERE adder_id = :session_id";
$param1 = array ('session_id' => $_SESSION['id']);
$cliques = $db->query($select, $param1);
foreach($cliques as $key)
{
$array[] = $key['clique_id'];
}
$array[] = $key['clique_id'];
$notijfy = new Notification();
$notijfy->addCircle($array);
function addCircle($id_involve){
$escaped_values = array_map('mysql_real_escape_string', array_values($array));
$sql2 = "INSERT INTO notification(id_involve) VALUES (:id_involve)";
$param2 = array ('id_involve' => implode(", ", $escaped_values));
$result2 = $this->db->query ($sql2, $param2);
}

There are several ways.
I would just do something simple like this:
foreach($cliques as $key){
$array[] = $key['clique_id'];
}
$notijfy = new Notification();
$notijfy->addCircle($array);
function addCircle($array){
$insert_string = '';
$count = 0;
foreach ($array as $k => $v){
$count++;
${$k} = mysqli_real_escape_string($this->db, $v);
$insert_string .= "(" . ${$k} . ")";
if ($count < sizeof($array)){
$insert_string .= ",";
}
}
$sql2 = "INSERT INTO notification(id_involve) VALUES $insert_string;";
$result2= $this->db->query ($sql2, $param2);
}
Your major error is that you are trying to pass ($passing an array when calling the function, but in the function itself your argument is listed as $id_involve, when you obviously need an $array variable that you are using in the function itself. I also can't understand why are you trying to add an element to the $array variable outside of foreach loop in the beginning. Doesn't make any sense.
Instead of $this->db just use your connection variable.

Related

How to generate a WHERE clause from an array with multiple AND-conditions

I have an HTML-table, where various selections can be made. The selected variables that contain the respective values, build the array $data[]. Now, with this array I would like to make an SQL request where all selected criteria should be met. This means, that I need the following request:
SELECT * FROM fruitgroups
WHERE $selection[1] = $value[1]
AND $selection[2] = $value[2]
AND $selection[3] = $value[3]
etc ...
Can anybody please help me with the loop that generates exactly the string:
...
$selection[1] = $value[1]
AND $selection[2] = $value[2]
AND $selection[3] = $value[3]
... etc ...
...that I need for the request?
Thank you in advance!
You can make a SQL request like this:
$selection = array("one", "two", "three");
$value = array("Tone", "Ttwo", "Tthree");
$concat = array();
foreach($selection as $key => $var){
$new = $selection[$key] . " = " . $value[$key];
array_push($concat, $new);
}
$concat = implode(" AND ", $concat);
$request = 'SELECT * FROM fruitgroups WHERE ' . $concat . ';';
echo $request;
Run example
Similar to the answer above, but keep it simple and don't forget the single quotes around the values:
$clauses = [];
foreach ($values as $i => $value) {
$conditions[] = "{$selection[$i]} = '$value'";
}
$query = "SELECT * FROM fruitgroups WHERE " . implode(' AND ', $conditions);
Even better, use an ORM like Eloquent:
$conditions = [];
foreach ($values as $i => $value) {
$conditions[$i] = $value;
}
$result = App\FruitGroups::where($conditions)->get();
I'm assuming you are sanitizing your inputs first, of course.

PHP update statement with arrays

Hi so I have an insert statement which works well, but need to create a separate update function which uses array keys and array values, which would be quite like the insert function but updates.
I have this for my insert
$sql = "INSERT INTO $tablename (".implode(",", array_keys($DATA).")" . " DATA ('".implode("','",array_values($DATA))."')";
connect()->query($sql);
This is what I have for my update so far but am stuck with it,
<?php
function updatethis (array $id, array $values, $tablename)
{
$sql = "UPDATE $tablename SET (".implode(",", array_keys($DATA)).")" . " DATA ('".implode("','",array_values($DATA))."')";
dbconnect()->query($sql);
}
?>
Therefore I would like help on the update feature please .
So I am getting an error with the UPDATE syntax
This is the part i am struggling with, i cna give further explanation, but i must have put in the wrong syntax to update the database after i click edit on the index page it calls the function just the syntax is incorrect.
also its php to mySQL
index page for PHP updatee fucntion
{
$values = array();
$idValues = array($idColumn => $id);
foreach($_POST as $key => $value)
{
if(!empty($value) && ($value != "Submit"))
{
$values[$key] = $value;
}
}
$result = update($idValues, $values, $tableName);
}
Edit: Error I am getting
edit has not been successfull from below
if(isset($_POST['Submit']))
{
if($result>0)
{
echo 'Edit has been successful. Return to index page';
}
else
{
echo 'Edit has not been successful.';
}
}
My code
function updateAll(array $id, array $values, $tablename)
{
$sIDColumn = key($id);
$sIDValue = current($id);
$arrayValues = $values;
array_walk($values, function(&$value, $key){
$value = "{$key} = '{$value}'";
});
$sUpdate = implode(", ", array_values($values));
$sql = "UPDATE {$tablename} SET {$sUpdate} WHERE {$sIDColumn} = '{$sIDValue}'";
connect()->query($sql);
}
My aim: takes the input of the unique identifier of the row to be edited as an array of 1 then the value plus the name of the column representing the primary key, an array containing the values indexed by the column names as well as a string representing the table name useing array_keys and array_vaules like th insert but to update
You cannot UPDATE in the same way of INSERT. It should be like this :
$valueSets = array();
foreach($values as $key => $value) {
$valueSets[] = $key . " = '" . $value . "'";
}
$conditionSets = array();
foreach($id as $key => $value) {
$conditionSets[] = $key . " = '" . $value . "'";
}
$sql = "UPDATE $tablename SET ". join(",",$valueSets) . " WHERE " . join(" AND ", $conditionSets);
See details here http://dev.mysql.com/doc/refman/5.7/en/update.html
I believe the pattern you are using is incorrect?
UPDATE table SET (rows) DATA ('values');
I think updates look more like this:
UPDATE table SET row1 = 'value1', row2 = 'value2';
In which case, this may be closer to what you are looking for.
function updatethis(array $id, array $values, $tablename)
{
$sIDColumn = key($id);
$sIDValue = current($id);
$arrayValues = $values;
array_walk($values, function(&$value, $key){
$value = "{$key} = '{$value}'";
});
$sUpdate = implode(", ", array_values($values));
$sql = "UPDATE {$tablename} SET {$sUpdate} WHERE {$sIDColumn} = '{$sIDValue}'";
dbconnect()->query($sql);
}
Using it, I get this query:
$testArray = array(
"id" => 19,
"username" => "test"
);
updatethis(array("id" => 9), $testArray, "users");
UPDATE users SET id = '19', username = 'test' WHERE id = '9'
I hope this at least helps but when it comes to databases, I only know MySQL and it is possible you are using another language.
I think you can try something like this :
$champs : Array of fields to update
$valeurs : Array of value to update fields
$conditions : Array of conditions
protected function modify($table,$champs,$valeurs,$conditions){
$Requete = "UPDATE ".$table." SET ";
$nbChamps = count($champs);
$nbValeurs = count($valeurs);
if($nbChamps == $nbValeurs){
for($i = 0; $i < $nbChamps ; $i++){
if($i < ($nbChamps - 1)){
if(is_numeric($valeurs[$i]))
$Requete = $Requete.$champs[$i]." = ".$valeurs[$i].",";
else
$Requete = $Requete.$champs[$i]." = '".$valeurs[$i]."',";
}
else
if(is_numeric($valeurs[$i]))
$Requete = $Requete.$champs[$i]." = ".$valeurs[$i]." ";
else
$Requete = $Requete.$champs[$i]." = '".$valeurs[$i]."' ";
}
$Requete = $Requete.$this->genereConditions($conditions);
$this->db->query($Requete);
}
else
throw new Exception("Le nombre de champs n'est pas identique au nombre de valeurs", 1);
}
private function genereConditions($conditions){
$condition = "WHERE ";
for($i = 0 ; $i < count($conditions); $i++){
if($i < (count($conditions)) - 1)
$condition = $condition.$conditions[$i]." AND ";
else
$condition = $condition.$conditions[$i];
}
return $condition;
}

PHP list to an Array to a foreach Joomla Module

I have the following PHP, that needs to take a list of article ids and run it through a function to get them all from the database.
I am very much a beginner in PHP so far I have:
list($slide1, $slide2, $slide3, $slide4, $slide5) = explode(" ", $params->get('id'));
$a = array(
$item => $slide1,
"two" => $slide2,
// "three" => $slide3,
// "four" => $slide4,
// "five" => $slide5
);
foreach ($a as $k) {
$args['id'] = $k;
$item = ModArticleSlider::getArticles($args);
}
and the class:
class ModArticleSlider {
public function getArticles($args){
$db = &JFactory::getDBO();
$item = "";
$id = $args['id'];
if($id > 0){
$query = "select * ";
$query .= "FROM #__content WHERE id =".$id." AND state=1 " ;
//echo $query;
$db->setQuery($query);
$item = $db->loadObject();
}
return $item;
}
}
How would i get it so that instead of specifying $item to have it almost dynamic so that i can get all the selected articles and place them in different variables.. or would i have to place them in a array?
Any Advice/Answers Greatly Appreciated.
Another approach, and possibly more performant as it would require only one database query (versus one for each article), would be to use http://docs.joomla.org/JDatabase::loadObjectList
So, you could instead pass an array of your articles ids as $ids to your class like:
public function getArticles($ids){
if ($ids) {
$db = JFactory::getDbo();
$query = "SELECT * FROM #__content WHERE id IN (" . implode(',', $id) . ") AND state=1 " ;
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
return FALSE;
}
$rows is returned as an array so you can then process it as needed.
i am also beginner of PHP.
Please Try this:
foreach ($a as $k => $val) {
$args = $val;
$item[] = ModArticleSlider::getArticles($args);
var_dump($item);
}
in your class
simply
$id = $args;
i hope it will help you!
Store the articles into an array, you can try this:
$slides = explode(" ", $params->get('id'));
$articleArray = array();
foreach($slides as $slide) {
$articleArray[] = ModArticleSlider::getArticles($slide);
}
var_dump($articleArray);

Reverse mysql_fetch_assoc (mysql_set_assoc/mysql_encode_assoc)

Is there function encoding an associative array to use in a mySQL INSERT command?
This way you could do:
$array = mysql_fetch_assoc($result);
$array['key'] = 'updated_value';
mysql_query('INSERT INTO table ' . mysql_encode_assoc($array));
mysql_encode_assoc input:
array(
'name' => 'bob',
'vehicle' => 'car'
)
mysql_encode_assoc output:
'(name, vehicle) VALUES(bob, car)'
There is now:
function mysql_encode_assoc($array) {
$kenc = Array();
$venc = Array();
foreach($array as $k=>$v) {
$kenc[] = "`".mysql_real_escape_string($k)."`";
if( $v === null) $venc[] = "NULL";
else $venc[] = '"'.mysql_real_escape_string($v).'"';
}
$keys = "(".implode(",",$kenc).")";
$vals = "(".implode(",",$venc).")";
return $keys." VALUES ".$vals;
}
There's no built in function that I'm aware of. But you can quite easily make on using array_keys() and array_values().
No built-in function.
$sql = array();
foreach ($anArray as $f=>$v) $sql[] = "`{$f}`" = "'".mysql_real_escape_string($v)."'";
$query = "INSERT INTO table SET ".join(",", $sql);

Concatenation of string with a specific array elements

the given code below insert data from an array to the mysql table.as its not the full code but what i want to know is available in this code. my question is that there is a field in table named "image_url" but the data in that field only have image name and i want to append http://www.xxxxxx.com at the start of every image name and the replace it with the image name in the field but i dont know how to do that plz help me out
thanks in advance
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (".implode(',',array_keys($v)).") VALUES ('".implode("','",$v)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}
This snippet should do what you want:
if (isset($v['image_url'])) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
}
You can concatenate strings with the dot "."!
At first... Is your application protected against SQL injection? If not you should build two methods/functions like this using mysql_real_escape_string():
function sqlSafeKey( $key){
return '`' . mysql_real_escape_string( $key) . `'`;
}
function sqlSafeValue( $value){
return "'" . mysql_real_escape_string( $value) . "'";
}
And than use array_map() to escape your values like this:
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
About your question... The matzino's answer is correct and whole loop should look like this:
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
$query = "INSERT INTO test (".implode(',', $keys).
") VALUES ('".implode("','",$values)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}

Categories