Generate a comma separated list from Session Array - php

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.

Related

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

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 create custom CSV files using PHP?

In the $csv_array_attributes[0] represents every column for my csv file. sku is the product id. In $csv_array_attributes[0] represents all of the product ids for my csv(which is the rows value form column sku). In the query below I extract all of the products ids, attributes names and attributes values. My problem is that I have to compute my $csv array in order to assign for each attribute name(columns) the attribute values. In $final_string somehow I want to memorize all of the attributes values for a products (see the commented part). Thx in advance for the help. Im really stuck with this :(
$csv_array_attributes[0] = "sku%%".$header;
//GETTING ATTRIBUTES VALUES
$i = 1;
foreach($xml->children() as $content){
$id_produs = $content->ProductCode;
$csv_array_attributes[$i] = $id_produs;
$i++;
}
$select = mysql_query("SELECT id_prod.id_produs, GROUP_CONCAT('^^',nume_attr) AS nume_at, GROUP_CONCAT('^^',val_attr) AS val_at FROM attributes
INNER JOIN id_prod
ON id_prod.id_id_produs = attributes.id_produs
GROUP BY id_prod.id_produs");
$i = 0; $id_prod = array();
while ($row = mysql_fetch_array($select)){
$id_produs = $row['id_produs'];
$nume_attr = explode(",^^",substr($row['nume_at'],2));
$val_attr = explode(",^^",substr($row['val_attr'],2));
$id_prod[$id_produs] = $nume_attr;
$i++;
}
// var_dump(count($id_prod));
$nume = explode("%%", $csv_array_attributes[0]);
$csv[0] = $csv_array_attributes[0];
$i = 1;
foreach ($id_prod as $key => $value) {
// comment part
//$final_string = "";
//if (attr_name has attribute_value for product i ){
// $final_string.= attribute_value."%%";
//}else{
// $final_string.= "%%";
//}
//end comment part
$csv[$i] = $csv_array_attributes[$i]."%%".$final_string;
$i++;
}
//var_dump($csv_array_attributes[0])
//CREARE CSV
$file = fopen("attributes.csv","w+");
foreach ($csv as $line){
fputcsv($file,explode('%%',$line),"^","`");
}
To see the current result please click HERE
Actually I only can give you a hint how I would create a array for csv.
// header
$csv[0][0] = "one";
$csv[0][1] = "two";
$csv[0][2] = "three";
$csv[0][3] = "four";
$csv[0][4] = "five";
// body
$csv[1][0] = "some";
$csv[1][1] = "values";
$csv[1][2] = "that";
$csv[1][3] = "could";
$csv[1][4] = "be";
$csv[2][0] = "here";
$csv[2][1] = "in";
$csv[2][2] = "this";
$csv[2][3] = "little";
$csv[2][4] = "array";
This is only a sample to view the array setup.
If you have set up the header, lets say by a for you can fill the 2 demensional array.
If this is set up you can use a foreach to build your CSV
Sample
$seperator = ";";
$ln = "\r\n";
$csv_output = "";
foreach($csv as $c){
foreach($c as $value){
$csv_output .= $value . $seperator;
}
$csv_output . $ln;
}
csv output
one;two;three;four;five;
some;values;that;could;be;
here;in;this;little;array;
a row;with an;;empty;field;
empty fields are no problem since you seperate them all with a ;

Foreach is showing "Array" instead of selected items from dynamically generated checkboxes

I'm trying to capture a user's checkbox selection from a dynamically generated list of options but I'm getting "Array" instead of the names selected.
In my last test, I checked 2 of the three boxes and got 3 instances of "Array" back.
This is my query that finds the names:
$query = "SELECT id, first_name, last_name
FROM users WHERE location_id = " . $location_id;
$result = mysqli_query($connection, $query);
if (!$result)
{
die("Database query failed: " . mysqli_error($connection));
}
while ($row = mysqli_fetch_array($result))
{
$name = $row['first_name'] . " " . $row['last_name'];
echo '<label><input type="checkbox" name="emp_name[]" id="emp_name[]" value="' . $name . '"> ' . $name . '</label>';
}
I then post the array of names like this:
$attendee = $_POST['emp_name'];
And try to generate the list of names for my email like this:
$values = ('emp_name');
foreach ($values as $value) {
$$value = (array)$_POST[$value];
}
for($i = 0; $i < count($attendee); $i++){
$attendees = array();
foreach ($values as $value) {
$attendees[] = ${$value}[$i];
}
Can someone help me see what's wrong?
I changed my code and included a part of the html that I'm trying to render:
foreach ($attendee as $name) {
$attendees[] = $name;
$htmlBody .= "<tr><td>{$attendees}</td></tr>";
}
But it still returns Array.
Not sure why you do this:
$attendee = (array)$_POST['emp_name'];
Try to replace it with:
$attendee = $_POST['emp_name'];
From your question it's not too clear, but I think you're creating an array within an array,and that that's the issue.
If the above doesn't help, try to var_dump() the variable that gives you "Array" response, and you'll see what's within it.
EDIT: In addition to the change above, try to make this change too:
Replace all this code:
$values = ('emp_name');
foreach ($values as $value) {
$$value = (array)$_POST[$value];
}
for($i = 0; $i < count($attendee); $i++){
$attendees = array();
foreach ($values as $value) {
$attendees[] = ${$value}[$i];
}
with:
foreach ($_POST['emp_name'] as $name) {
$attendees[] = $name;
}
EDIT #2:
According to your code:
foreach ($attendee as $name) {
$attendees[] = $name;
$htmlBody .= "<tr><td>{$attendees}</td></tr>";
}
It's totally normal that you're getting Array instead of a name. See, by writing:
$attendees[] = $name;
you're implying to php that it's an array. On the other hand the foreach loop does the opposite thing, it takes each of the values from $attendee array and makes it available to you as $name variable. So you're basically doing the right thing, and then reverting it back to array for no reason.
SOLUTION:
Replace {$attendees} with {$name}. And it should work.
You can write that with alot less code.
$attendees will now contain your checked checkboxes.
$attendees = array()
foreach($_POST['emp_name'] as $name){
$attendees[] = $name;
}

How do i merge matching strings in an array?

Hi I currently have this code that retrieves the tags from each Image in the Database. The tags are seperated by commas. I place each set of tags on the end of the array. Now I want to create an array of the tags retrieved but merge any duplications.
function get_tags()
{
$tag_array = array();
$query = mysql_query("
SELECT tags
FROM gallery_image
");
while($row = mysql_fetch_assoc($query))
{
$tags = $row['tags'];
$tag_array[] = $tags;
}
echo $tag_array[0] . '<br>' . $tag_array[1] . '<br>' .$tag_array[2];
}
You question is not very clear but array_unique may be what you need?
function get_tags()
{
$query = mysql_query('SELECT tags '.
'FROM gallery_image');
$tag_array = array();
while($row = mysql_fetch_assoc($query))
$tag_array = array_merge($tag_array, explode(',', $row['tags']));
return array_unique($tag_array);
}
You probably want something like this:
$tags = array(
'one,two',
'one,three',
);
$result = array_unique(array_reduce($tags,
function($curr, $el) {
return array_merge($curr, explode(',', $el));
},
array()));
See it in action.
What this does is process each result row (which I assume looks like "tag1,tag2") in turn with array_reduce, splitting the tags out with explode and collecting them into an intermediate array which has just one tag per element. Then the duplicate tags are filtered out with array_unique to produce the end result.
Try this:
$unique_tags = array();
foreach ($tag_array as $value) {
$unique_tags = array_merge($unique_tags, explode(",", $value);
}
$unique_tags = array_unique($unique_tags);

Categories