Placing SQL query results into one array - php

I have this PhP script:
<?php
$gregorianMonth = date(n);
$gregorianDay = date(j);
$gregorianYear = date(Y);
$jdDate = gregoriantojd($gregorianMonth,$gregorianDay,$gregorianYear);
$hebrewMonthName = jdmonthname($jdDate,4);
$hebrewDate = jdtojewish($jdDate);
list($hebrewMonth, $hebrewDay, $hebrewYear) = split('/',$hebrewDate);
?>
<?php
$table_name = "candle_number";
$data = $wpdb->get_results( "SELECT email FROM `{$table_name}` WHERE `datehebrew` LIKE '%%$hebrewDay%%' AND `datehebrew` LIKE '%%$hebrewMonth%%' AND date_pref = \"hebrew\"");
foreach( $data as $rs ){
echo "
<p>{$rs->email}</p>
";hat I can
$i++;
}
?>
And what I was initially thinking was to use a foreach loop with the CURL Mailchimp API to send each email to my endpoint, kind of a one off.
BUT - I know that the foreach might not loop process and it's not very clean. I think the BETTER solution would be to have every result put into an array then send THAT array in the curl, because the MC API will accept it.
I am still kind of a novice though so this is where I am stuck. So how can I take those results from my query and put them into one string?

Try:
//create blank array
$final_output = array();
foreach( $data as $rs ){
//add data to array in next index.
final_output[] = $rs->email;
$i++;
}
//at this point send your data array wherever you want.
print_r($final_output);
If you want to convert your data to string use:
echo json_encode($final_output);

Related

How to access whileloop record outside the loop using array

Hello i selected all records from users and returned them using a php whileloop and array, using implode i could get all the records outside the loop, what i wish to do actually is to access individual record and assign them to a variable individually to be used later in the same page.
this is what i came up with already, it works, but i don't know how to assign the recorded to individual variables, since all the records are displayed using implode
`<?php
$data = array();
$query = "SELECT * FROM users ";
$queryResult = mysqli_query($conn,$query);
while($_row = mysqli_fetch_array($queryResult)){
$data[] = $_row['first_name'];
$data[] = $_row['email'];
$data[] = $_row['amount'];
?>
<?php }?>
<?php
echo "<br />";
$request = implode("<br />", $data);
echo $request;?>`
please i need assistance on how to achieve or a better way to access whileloop records outside the loop this thanks in advance
This is what i intended doing with that result of the loop in the next query
`<?php
$profit = 10;
$query = "UPDATE storage SET ";
$query .="store_profit = '{$profit}' ";
$query .= "WHERE email = '{$email_from_loop_above}' ";?>`
for clarity purposes.. this script will be executed by a cronjob every 1 minute, initially this is what is did..
`
<?php
$query = "SELECT * FROM users WHERE email = $_SESSION['email'] ";
$queryResult = mysqli_query($conn,$query);
while($_row = mysqli_fetch_array($queryResult)){
$first_name = $_row['first_name'];
$email_from_loop_above = $_row['email'];
$amount = $_row['amount'];
?>
<?php }?>`
Then for the update query this is what i did
`<?php
//The profit below was gotten from a percent from the amount i return from the loop above.
$profit = 10;
$query = "UPDATE storage SET ";
$query .="store_profit = '{$profit}' ";
$query .= "WHERE email = '{$_SESSION['email']}' ";
?>`
Now this code above works perfectly, but when the user logout out the store_profit would not update anymore simply because this you know would require an active user SESSION to work, so what i am trying to do now is is make it work accordingly even when the user is logged out of the account, if i use the following method
`<?php
$query = "SELECT * FROM users ";
$queryResult = mysqli_query($conn,$query);
while($_row = mysqli_fetch_array($queryResult)){
$first_name = $_row['first_name'];
$email_from_loop = $_row['email'];
$amount = $_row['amount'];
?>
<?php }?>`
`
<?php
$profit = 10;
$query = "UPDATE storage SET ";
$query .="store_profit = '{$profit}' ";
$query .= "WHERE email = '{$email_from_loop}' ";
?>`
it would only return the last user data only, simply because i am outside the loop, now when i try to update inside the loop, it works but it adds 10 to store_profit to the first user and adds 20 to the second user also adds 30 to third user... simply because it inside the loop
now what is want to do is make this work accordingly so i decided to use array, however i am not to familiar with array that why i became confused.
An explanation of how i can achieve this purpose would be very much appreciated thanks.
however i was thinking of not destroying all the user session maybe i create session for that purpose and not distroy it.. but i don't if that method would be safe or good.
As a result of your loop you have a $data array which you then turn into a string by gluing all its elements using implode function.
You can of course still access every individual element of $data array outside of the loop by addressing to its direct index.
For instance:
echo $data[0]['email'];
will output the email record of first (arrays are 0 based in PHP) element of your array.

Build a php array in foreach loop that I can sort

I have a foreach loop that goes through to get information related to a photo.
It's basically this
foreach($medias as $image) {
$fullImage = $image->imageHighResolutionUrl;
$standardRes = $image->imageStandardResolutionUrl;
$caption = $image->caption;
$createdTime = date("Y-m-d",$image->createdTime);
$imageCode = $image->code;
}
Now I want to put that data into an array (I'm assuming), so I can sort it by $createdTime then loop through the data to run an "INSERT INTO table" mysql query for each photo.
I think you can store the data into an array by the following way -
$sl = 0;
foreach($medias as $image) {
$data[$sl]['fullImage'] = $image->imageHighResolutionUrl;
$data[$sl]['standardRes'] = $image->imageStandardResolutionUrl;
$data[$sl]['caption'] = $image->caption;
$data[$sl]['createdTime'] = date("Y-m-d",$image->createdTime);
$data[$sl]['imageCode'] = $image->code;
$sl++;
}
echo print_r($data);
Now you can a sort the $data variable whatever you want. Then loop through the data and entry into Database.
let me know if you any problem there.

getting all values from array with 'list' and #foreach'

i try to list a overview for a gallary by using 'list' and 'foreach' , but i always get just one (the oldest) result from my database.
i use this
while($row = mysql_fetch_array($result)){
$galpath1 = "galerie/";
$gal_title = $row['gal_title'];
$gal_path= $galpath1.$row['uploads'];
$nickname = $row['nickname'];
$added = $row['format_date'];
$galshow = [
[$gal_path, $gal_title, $added],
];
}
if(!empty($gal_path))
{
var_dump($galshow);
foreach ($galshow as list($gal_pathes, $gal_titles, $addeds)) {
List of galerys
}
how can i bring it to work so that i can list all gallerys that matches the select in my database?
Thank you so much cdhowie
you saved my day. that was exactly what i did wrong.
so thanks for the quick response. :)
Every iteration of the while loop you overwrite the value in $galshow with a new array containing one element. As a result, this array will only ever contain one element, and it will be the last row fetched from the database.
Instead, create a new array outside of the loop and append to it inside the loop:
$galshow = array();
while($row = mysql_fetch_array($result)){
$galpath1 = "galerie/";
$gal_title = $row['gal_title'];
$gal_path = $galpath1.$row['uploads'];
$nickname = $row['nickname'];
$added = $row['format_date'];
// This syntax will append a new array to the end of the $galshow array.
$galshow[] = [$gal_path, $gal_title, $added];
}

How to print multiple ID's from a $_GET variable using while() and array()

I'm here today because i'm under a minor issue that i can't seem to solve and it's why it brings be here.
The issue is that i'm trying to get multiple ID's from a $_GET variable to print out. I tried to use array and great, it works but the thing is it makes separate arrays with [0] and i need it to be as one in the same array not array() array() which is what its doing.
So i'm using while() with mysql_fetch_array to get the results off the database and it depends on the $_GET from the url in-order to grab the correct id's. So in the URL i pass in api.php?do=remove&id=1,4,7 it will only print out the first id and not the others as a name. As i said i tried with array() and this is what came out :
Array
(
[0] => BzlXO.jpg
)
Array
(
[0] => cHZTk.jpg
)
Array
(
[0] => 9yset.jpg
)
Array
(
[0] => Ss04V.jpg
)
i don't understand why its doing that as i need it to be in one array as in
Array (
[0] => BzlXO.jpg,
[1] => cHZTk.jpg,
[2] => 9yset.jpg,
[3] => Ss04V.jpg
)
So that way when i implode them it will show as text as in:
"You removed image(s) "BzlXO.jpg,cHZTk.jpg,9yset.jpg,Ss04V.jpg"
with something like
$iName[imagename] = array($iName[imagename]);
$name = implode(",", $iName[imagename]);
Here is my code:
This is the URL "api.php?do=remove&id=1,4,7"
$ID = $_GET['id'];
$query = "SELECT ID,imagename FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$result = mysql_query($query);
while( $iName = mysql_fetch_array($result)){
$querys = "DELETE FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$results = mysql_query($querys);
if(!$results) {
$api_message = 'Failed to get a Removal result';
} else {
$iName[imagename] = array($iName[imagename]);
$name = implode(",", $iName[imagename]);
$api_message = "You removed image(s) $name";
}
}
The OUTPUT :
You removed image(s) BzlXO.jpg
but i need it to be:
The OUTPUT :
You removed image(s) "BzlXO.jpg,cHZTk.jpg,9yset.jpg,Ss04V.jpg"
Any help with this will be much appreciated, if any more information is needed please let me know and i'll include
Thanks
In addition to the solution posted by raina77ow, there is also a problem with the control flow in that you are executing the DELETE FROM uploads WHERE ID IN (...) statement for each iteration of the while loop. This will delete all the records on the first iteration. You need to change it to something like:
$ID = $_GET['id'];
$names = array();
$query = "SELECT ID,imagename FROM uploads WHERE ID IN ({$ID}) AND username = '{$uploader}'";
$result = mysql_query($query);
while( $iName = mysql_fetch_array($result)){
$querys = "DELETE FROM uploads WHERE ID = {$iName['ID']} AND username = '{$uploader}'";
$results = mysql_query($querys);
if(!$results) {
$api_message = 'Failed to get a Removal result';
} else {
$names[] = $iName['imagename']);
}
}
$name = implode(",", $names);
$api_message = "You removed image(s) $name";
Perhaps you need to fill an array declared before the loop instead, like that:
$images = array();
while( $iName = mysql_fetch_array($result)) {
...
$images[] = $iName['imagename']; # pushing the deleted image into that array
}
...
$names = implode(', ', $images);
And I strongly suggest at least checking the possibility of using mysqli set of functions instead (or PDO, that's even better in my opinion, but might be a step too huge for your codebase). )
You should revise your code as to protect it against invalid values and reduce the possibility of failures.
As to your specific problem, there's no need to place values from one array inside another one, just to the goal of imploding it to a string. You can simply use string concatenation to keep adding the desired values.
This suggestion fixes you issue: code comments are to explain whats happening
// initialize the user message with the success string
$api_message = "You removed image(s): ";
// check if the URL variable exists and contains values
if (isset($_GET['id']) && $_GET['id']!='') {
// clean the values a litle bit to prevent code injection
$ID = strip_tags(trim($_GET['id']));
// prepare the query (more compatible string concatenation)
$query = "SELECT ID, imagename FROM uploads WHERE ID IN (".$ID.") AND username = '".$uploader."'";
// query the databse
$result = mysql_query($query);
// check for results
if (is_resource($result) && mysql_num_rows($result)>=1) {
// get total records
$counter = mysql_num_rows($result);
// run by each result found
while($iName = mysql_fetch_array($result)) {
// delete all from the database
$querys = "DELETE FROM uploads WHERE ID IN (".$ID.") AND username = '".$uploader."'";
$results = mysql_query($querys);
// check if the returned result is false
if (!$results) {
// replace the user message with a fail information
$api_message = 'Failed to get a Removal result';
} else {
// decrease the counter
$counter--;
// update the user message and add a "," if this is not the last name
$api_message.= $iName['imagename'] . (($counter==0)?(''):(', '));
}
}
} else {
$api_message = 'ups... failed to talk with the database';
}
} else {
$api_message = 'ups... no ids collected';
}
Related reading:
PHP strip_tags
strip_tags — Strip HTML and PHP tags from a string
PHP trim
trim — Strip whitespace (or other characters) from the beginning and end of a string
PHP is_resource
is_resource — Finds whether a variable is a resource

Make array with arrays from a mysql query

Working on a e-shop, i must read from the DB the products that have productpack not null.
productpack from the DB looks like this : 0141,3122,0104,0111,3114,0106,0117 .
I'm trying to get all the DB items that have productpack set (not null), and make them into an array with arrays with those codes (0141,3122,0104,0111,3114,0106,0117).
function p_productpacks(){
$productpacks = array();
$pack = array();
$q = mysql_query('SELECT productpack FROM products WHERE productpack <> "";');
while($p = mysql_fetch_object($q)){
$pack = explode(",", $p);
$productpacks[] = $pack;
}
return $productpacks;
}
You need to create an array otherwise, you're overwriting existing packs:
$pack = explode(",", $p->productpack);
$productpacks[] = $pack;
For more information read about array_pushDocs and PHP Arrays Docs (and mysql_fetch_objectDocs).
You can get all productpacks in a CSV array using:
$result = mysql_query("SELECT GROUP_CONCAT(productpack) as productpacks
FROM products WHERE productpack <> '' ");
if ($result) {
$row = mysql_fetch_row($result);
$productpacks_as_CSV_string = $row['productpacks'];
}
That way you only need to get one row out of the database, saving lots of time.
See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
mysql_fetch_object returns an object and can't be used with string processing.. if you definitely want to use this, you need to do something like:
$pack=explode(',',$p->productpack);
$productpacks[]=$pack
Or, to use a good old array instead:
while ($p = mysql_query($q))
{
$pack = explode(",", $p['productpack']);
$productpacks[] = $pack;
}

Categories