Php : variable not transmitted into a foreach - php

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;

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.

Match rows against elements in an array

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');
}
}

Access JSON array in PHP and send to MySQL SELECT

I'm trying to receive the data from JSON with PHP and use it in my SELECT query. I have searched everywhere and every solution didn't worked for me.
My Returned JSON data:
"{processos:[{"processo":"203"},{"processo":"1430"}]}"
My PHP:
$ar2 = json_decode($processo2, true);
$where2 = array();
foreach($ar2['processo'] as $key=>$val){
$where2[] = $val;
}
$where2 = implode(',', $where2);
$pegaSonda = $pdo->prepare("SELECT * FROM sonda WHERE n_processo IN ($where2)");
$pegaSonda->execute();
What's wrong with my code?
EDIT
The code from #wadersgroup worked correctly, but when i change to my variable it stops. This is the way i'm encoding it:
$jsonData = array();
$jsonData[] = array("processo" => $automovel->n_processo);
$data['processo2'] .= '{"processos":'.json_encode($jsonData).'}';
$data['processo2'] is sending to my AJAX to populate the input and then it receive data back with:
$processo2 = strip_tags(stripslashes($_POST['n_processo2']));
There are many errors in this code. Try this
$ar2 = json_decode('{"processos":[{"processo":"203"},{"processo":"1430"}]}', true);
$where2 = array();
foreach($ar2['processos'] as $key=>$val){
$where2[] = $val['processo'];
}
$where = implode(',', $where2);
print_r($where);
Your JSON string looks invalid, try instead:
'{"processos":[{"processo":"203"},{"processo":"1430"}]}'
$processo2 = '{"processos": [{ "processo": "203"},{ "processo": "1430"}]}'
$ar2 = json_decode($processo2, true);
$arr = array_map(function($i) {return $i['processo']; }, $ar2["processos"]);
$where = implode(", ", $arr);

Sending delimited from textarea to mysql. Column by "," and row by "\n"

I need a user to be able to enter data into a textarea in the following format.
name,email#email.com
name,email#email.com
name,email#email.com
The information would then be sent to the mysql database. My issue is that I want to place the proper name into the first column and the proper email into the second column. Then, when I encounter a line break I would like it to start a new row.
Can anyone help with this? Thanks!
As others have said you can use explode to get the results into an array however, the problem with this approach is there is no guarantee the user will enter the information in the correct order.
What I would do is this. It's still not fool proof (And using separate inputs would be better) but it's better.
<?php
$textareastring = $_POST['textareaname'];
$array = explode("\n",$textareastring );
foreach($array as $value) {
$data = explode(',',$value);
if (strpos($data[1], '#'))
{
$name = $data[0];
$email = $data[1];
}else{
$name = $data[1];
$email = $data[0];
}
}
?>
I would use explode() to separate the different lines and then the fields. Like that:
$lines = explode("\n", $_POST['textarea']);
foreach($lines as $line) {
$fields = explode(',', $line);
$name = $fields[0];
$email = $fields[1];
// DO YOUR MYSQL STUFF HERE
}
There might be better ways out there, but that would work for you.
<?php
$textareastring = $_POST['textareaname'];
$array = explode("\n",$textareastring );
foreach($array as $value) {
$data = explode(',',$value);
$name = $data[0];
$email = $data[1];
//Your mysql query goes here
}
?>

stip slashes from database return with while loop

Can I loop through DB results and remove Slashes?
(I started getting more slashes everytime I edited the text and put it back into the DB)
$db = new connection();
$query = "SELECT * FROM ITEMS, ALPACA_SALES WHERE ITEMS.uid = '$id' AND ALPACA_SALES.uid = ITEMS.uid";
$results = $db->query($query);
$data = array();
while($info = mysql_fetch_array($results))
{
$data[] = stripslashes($info);
}
But I am getting the following error:
Notice: Array to string conversion in /home/content/myfile.php on line 78
When I add the data to the database I do the following:
if (!empty($_POST['more_text']))
{
$more_text = addslashes($_POST['more_text']);
}
else
{
$error = false;
$error_message = "Please add a description.";
}
And then I use UPDATE for the insert into the DB:
$query2 = "UPDATE ALPACA_SALES SET more_text = '$more_text' WHERE uid = '$id'";
$result = $db->query($query2);
You can't run stripslashes() on an array, which is what $info is from storing mysql_fetch_array($results). You could iterate through $info and strip slashes on each entry, or explicitly strip slashes if you don't need to do all of them.
$i=0;
while($infoarray = mysql_fetch_assoc($results))
{
foreach($infoarray as $field=>$value){
$data[$i][$field] = stripslashes($value);
}
$i++;
}
Edit: You can also create a small function to strip slashes in an array, as outlined in the documentation here: http://us.php.net/manual/en/function.stripslashes.php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
Do not do that. stripslashes() is not enough to make a string safe to use in an SQL statement. Your code is vulnerable to SQL injection. Use prepared statements and bound parameters instead.

Categories