Match rows against elements in an array - php

I have a sql request to do with a php array to find all the occurrences of a search bar.
I can't get this done. This is my code :
$texte = $_POST['texte'];
$texte = explode(" ", $texte);
$query_parts = array();
//Proximité
foreach ($texte as $value) {
$value = "%".$value."%";
}
$sql = "SELECT * FROM PROXIMITE WHERE titrefr LIKE ':texte'";
$req = $bd->requete_obj($sql, array('texte'=>$texte));
while($select = $req->fetch()){
error_log('Test');
}

Your foreach-loop does not actually modify the variables, because they are passed by Value - meaning a copy.
to modify them, you have to pass them by reference:
foreach ($texte as &$value) {
$value = "%".$value."%";
}
that way, the actual values in your array are being manipulated.
secondly: you can not give your database an array as parameter. instead, you could loop through the array. if you implement that in your first loop, you don't even have to use references anymore:
$sql = "SELECT * FROM PROXIMITE WHERE titrefr LIKE :texte";
foreach ($texte as $value) {
$value = "%".$value."%";
$req = $bd->requete_obj($sql, array('texte'=>$value));
while($select = $req->fetch()){
error_log('Test');
}
}

Related

Loop through list of form elements array to get or fetch the elements we need or want to keep

This is my current code, I'm looking for a more efficient way of writing it.
Need something like looping through each variable with a foreach or adding them all to an array somehow, without me having to re-write every variable name.
$formValues = $form_state->getValues();
$relocation = $formValues['relocation'];
$europe = $formValues['europe'];
$twoyears = $formValues['twoyears'];
$realestate = $formValues['realestate'];
$nominated = $formValues['check_nominated_by'];
$nom_comp = $formValues['nom_company'];
$nom_contact = $formValues['nom_contact'];
$nom_email = $formValues['nom_email'];
$contact1 = $formValues['contact1'];
$position1 = $formValues['contact_position1'];
$email1 = $formValues['email1'];
$contact2 = $formValues['contact2'];
$position2 = $formValues['contact2'];
$email2 = $formValues['contact2'];
$contact3 = $formValues['contact3'];
$position3 = $formValues['contact3'];
$email3 = $formValues['contact3'];
tempstore = array();
$tempstore['relocation'] = $relocation;
$tempstore['europe'] = $europe;
$tempstore['twoyears'] = $twoyears;
$tempstore['realestate'] = $realestate;
$tempstore['membertype'] = $membertype;
$tempstore['nominated_by'] = '';
// All other fields need to be in this array too
// But there are a lot of unwanted fields in the $formValues
$_SESSION['sessionName']['formName'] = $tempstore;
Seeing as you know the keys you'd like to keep you can do the following:
<?php
/** The keys you want to keep... **/
$keys_to_keep = [
];
/** Will be used to store values for saving to $_SESSION. **/
$temp_array = [];
/** Loop through the keys/values. **/
foreach ($formValues as $key => $value) {
/** The correct key i.e. the key you'd like to save. **/
if (in_array($key, $keys_to_keep)) {
/** What you wish to do... **/
$temp_array[$key] = $value;
}
}
$_SESSION['sessionName']['formName'] = $temp_array;
?>
What is happening is that you are looping through your $formValues and getting both the keys and values of each pair in the array.
Then an check is being done against your $keys_to_keep to see if the current element is the one you wish to keep, if it is then you save it in to $temp_array.
Reading Material
foreach
in_array
You can use variable variables and a foreach.
Foreach($formValues as $key => $var){
$$key = $var;
}
Echo $relocation ."\n" . $europe;
https://3v4l.org/QeLjp
Edit I see now that your array variable keys are not always the same as the variable name you want.
In that case you can't use the method above.
In that case you need to use list() = array.
List($relocation, $europe) = $formValues;
// The list variables have to be in correct order I just took the first two for demo purpose.

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 : variable not transmitted into a foreach

Probably a stupid question here, I apologize...
I have a SQL request into a foreach, like below.
The "auth" string is correctly defined, a "echo $auth" returns what I want. But the sql request returns nothing.
// $auth=something;
$val=array(value1,value2,value3);
foreach ($val as $j)
{
$req = mysqli_fetch_array(mysqli_query($link,"select val from user where auth='$auth'"));
$$j=$req[val];
}
My goal is to select the sql fieds contained in the $val array (it perfectly works in others parts of my project). Thanks in advance.
I also tried this, still does not return anything :
$val = array('mail','preferences','info','langue'); // This must be an array
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
$mail = $req[0]; $preferences = $req[1]; $info = $req[2]; $info = $req[3];
My goal is to select the sql fieds contained in the $val array
So the $val contains the fields you want to use on your query. You can use an explode() to retrieve all the fields without a foreach:
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
And the you can get the value:
$value1 = $req[$val[0]]; // First field
Okay, let's resume all that. so we have two methods. First :
$val=array(mail,preferences,info,langue);
foreach ($val as $j)
{
$auth = $_SESSION['auth'];
echo $auth; //this works
$req = "select val from user where auth='$auth'";//this works only in phpMyadmin
$req = mysqli_fetch_array(mysqli_query($link,$req));
$$j=$req[val];
}
echo $mail; //gives nothing of course...
And here's the second one :
val = array('mail','preferences','info','langue');
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
$mail = $req[$val[0]]; $preferences = $req[$val[1]]; $info = $req[$val[2]]; $info = $req[$val[3]];
Still nothing works. No php problem detected, my Mysqli instances work correctly... PLEASE do notice we are in debug mode, so my first code is not optimized of course...
The problem is the use of explode which splits a string on a delimiter and create an array. You already have an array, but you want to make it a string. To do this you can use implode:
$columns = array("mail", "preferences", "info", "language");
$sql = sprintf("SELECT %s FROM user WHERE auth='%s'", implode(",", $columns), $auth);
$query = mysqli_query($sql); //..fetch possible errors
$row = mysqli_fetch_array($query); //..make sure a row was returned
list($mail, $preferences, $info, $language) = $row;
echo $mail;

How to insert an array into a Mysql table

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.

Generate a comma separated list from Session Array

I have a session array [cart] of which contains user id numbers. I am trying to generate a list of email addresses from the contact table WHERE the contact id numbers in the session = the contact_id in the database.
Here is my code.
// Find cart members from the session array
foreach ($_SESSION['cart'] as $key=>$val) {
$contactid = $val;
// Query the database for cart members
$cartresult = mysql_query("SELECT contact.email FROM contact WHERE contact.contact_id = '$contactid'");
$emailresult = mysql_query($emailquery) or DIE (mysql_error());
while ($r = mysql_fetch_array($emailresult)) {
$emailAry[] = $r['email'];
}
}
// Create comma separated list from email array
if (count($emailAry)) {
$list = implode(", ", $emailAry);
$list = str_replace(" ,", "", $list);
Apparently there is no value for $emailAry because the if statement is being neglected.
Any idea why this would be?
$emailquery from my perspective is undefined.
$emailAry = array();
// Find cart members from the session array
foreach ($_SESSION['cart'] as $key=>$val) {
$cartresult = mysql_query("SELECT email FROM contact WHERE contact_id = '$val'");
while ($r = mysql_fetch_array($cartresult)) {
$emailAry[] = $r['email'];
}
}
// Create comma separated list from email array
if (count($emailAry)) {
$list = implode(",", $emailAry);
// no need to replace ', ' with '', implode will do all the job creating a CSV :)
//$list = str_replace(" ,", "", $list);
}
Declare the $emailAry array in the outer scope, so you can access it from the code out of the while and foreach, like his:
$emailAry = array();
foreach ($_SESSION['cart'] as $key=>$val) {
...
...
Use this it's easy and fast
$to = '';
foreach ($result->result() as $row){
$to .= $row->id.',';
}
$to = rtrim($to,',');
Change it according to yours.

Categories