Please see below code
$template->customer = $rephome->getCustomer($user_id);
foreach($template->customer as $value){
echo $value->customer_id;
}
The first line of code will get result of a query. it was fetched as object.
the second line of code will echo out all of the customer id field from the query result. This works fine. it will echo out 1234567.... to however many id there is.
however if I change the code to like the one below, the echo will only get the first customer_id. ie. 1
$template->customer = $rephome->getCustomer($user_id);
foreach($template->customer as $value){
$something = $value->customer_id;
}
echo $something;
so the question is what is the correct way of assigning the list of results to $something. so I can use $something as a list of ids to be used to run other querys.
in another word. I am trying to use result of first query to run a second query.
$template->customers = $rephome->getCustomer($user_id);
foreach ($template->customers as $value){
$template->orders = $rephome->getOrder($value->customer_id);
}
the above code give me the same result as echo. I will get all the customer id as intented but I will only get repeating order information that is assoicated with first customer id. instead of different orders associated to different customer id.
Yes of course, cause you are overwriting the $something variable each iteration of the foreach loop and echo the result afterwards.
A way to solve this is by using an array:
$something = array();
foreach($template->customer as $value){
$something[] = $value->customer_id;
}
This way you are adding a value to the array each iteration.
so the question is what is the correct way of assigning the list of
results to $something. so I can use $something as a list of ids to be
used to run other querys.
To use the ID's for another SELECT query, so it will only return records associated with the id's inside the array, you can do this for example:
$sql = 'SELECT * FROM `table`
WHERE `id` IN (' . implode(',', array_map('intval', $something)) . ')';
Which will result in something like:
$sql = 'SELECT * FROM `table` WHERE `id` IN (1,2,4,6,7,10)';
Does this answer your question?
On this code:
foreach($template->customer as $value){
$something = $value->customer_id;
}
$something will be overrriten on each loop for a new value. So, on last line, your code will output the last value of resultsetĀ“s $value->customer_id.
Got it ??
So, use an array:
$something = array();
foreach($template->customer as $value){
$something[] = $value->customer_id;
}
Try this within your loop:
$something[] = $value->customer_id;
and then outside your loop:
print_r($something);
Related
I'm trying to run a MYSQL query inside a foreach loop.
here's the scenario:
I have a comma separated string with some names in it.
I use explode() and foreach() to get the separate values/names from this comma separated string.
Then I need to search mysql database for each of these values/names that I get from this string and if that value exists in the database, I then get its ID and create a new recrord in another table in the database.
However, when I run my code, I only get the ID of the first instance from the comma separated string.
my mysql database looks like this:
id category_name
3 Hotel
4 Restaurants
This is my code:
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
///i do the explode and foreach here///
$arrs = explode(',', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
}
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>;
}
so when the i run my code, I get the ID of the Hotel twice like so:
3
3
I'm expecting it to be like below based on what I have in MYSQL:
3
4
Could someone please advice on this issue?
First of all such things should be done using prepared statements. Not only it is easier and faster, but also more secure. Remember to always use prepared statements.
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
$stmt = $db_conx->prepare('SELECT * FROM categories WHERE category_name=?');
$stmt->bind_param('s', $cat);
foreach(explode(',', $biz_cat) as $cat){
$cat = trim($cat); // remove extra spaces at the beginning/end
$stmt->execute();
// we fetch a single row, but if you expect multiple rows for each category name, then you should loop on the $stmt->get_result()
$row99 = $stmt->get_result()->fetch_assoc();
// echo it in the loop or save it in the array for later use
echo $row99['id'];
}
In the example here I prepare a statement and bind a variable $cat. I then explode the string into an array on which I loop straight away. In each iteration I execute my statement, which in turn produces a result. Since you seem to be interested only in the first row returned, we do not need to loop on the result, we can ask for the array immediately. If you would like to loop just replace
$row99 = $stmt->get_result()->fetch_assoc();
with
foreach($stmt->get_result() as $row99) {
echo $row99['id'];
}
Once you get the id in the array, you can either print it out or save it into an array for later use.
As of now, you are re-assigning a new value to scalar variable $catIDS for each record returned by the query, then you echo it one you are done looping. You would need to put the echo/insert logic inside the loop (or maybe store the values in array).
Another thing to note is that you are splitting with , (a single comma), but you have a space between the two words. As a result, the second value (Restaurant) starts with a space, which will cause the query to return an empty resultset. You probably want to split with , (a comma followed by a space).
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(', ', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>';
}
}
The code below can do what you need.
Update INSERT YOUR NEW DATA HERE
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(',', $biz_cat);
foreach ($arrs as $arr) {
$query99 = mysqli_query($db_conx, "SELECT * FROM categories WHERE category_name='$arr'");
while ($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)) {
$catIDS = $row99['id'];
// INSERT YOUR NEW DATA HERE
echo $catIDS . '<br/>';
}
}
I'm using PHP and I do a mysql query and I save the result of this query in an array. Then, I use a loop and into the loop i do another mysql query using the values of the array in the where clause. It's right but if I try to get the result of the query outside the loop I can't.
Here an example code
$result=$mysqli->query("SELECT code FROM referee");
$i=0;
$arcode=array();
while($row=$result->fetch_array()){
$arcode[$i]=$row["code"];
$i++;
}
for($j=0;$j<sizeof($arcode);$j++){
$result2=$mysqli->query("SELECT code, time FROM match where referee_code IN ($arcode[$j])");
}
/*Here I can't get the result values*/
$matcode=array();
$hour=array();
$k=0;
while($row2=$result2->fetch_array()){
$matcode[$k]=$row2["code"];
$hour[$k]=$row2["time"];
}
If I put all in the same loop I get the result repeated (This code is one example of all my code but the idea is the same in the rest).
You are overwriting the result set values into $result2.
The correct method would be something like:
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
while ($row2 = $result2->fetch_array())
{
$matcode[] = $row2["code"];
$hour[] = $row2["time"];
}
You may change the index values according to the way you want the array to look like.
Also match is a reserved word. So you would have to enclose it in backticks.
If you want to print complete data then try this :
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
$completeData=array();
while ($row2 = $result2->fetch_array())
{
$completeData[] = $row2;
}
print_r($completeData);
Don forget to accept answer if it helps :)
Just wondering if anyone can help me with this problem...
I want to be able to check if a certain ID (user for example is logged on) The ID's of these users will be pulled from a table, and then fed into an array and then checked if it is in there.
However when I pull the data the if inarray() no longer works as it would if I just typed it in straight within the code instead of pulling it.
I want to pull approved ID's through so they can access a certain link essentially!
Any help would be appreciated! Thanks!
<?php
mssql_select_db("$ins", $con);
$result = mssql_query("SELECT ID FROM Event WHERE EventPublic LIKE 'Yes' AND EventDate >= GETDATE() -1 ORDER BY EventDate ASC ");
while($row = mssql_fetch_array($result))
{
$test = "". $row['ID'] .",";
}
$tests = explode(',', $test);
if (in_array("2, 48", $tests)) {
echo "WOO";
}
else
{
echo "BOO";
}
mssql_close($con);
?>
in array should be an actual array
in_array(array('2', '48'), $tests)
also, it would be better to put
$tests = array();
before the while loop, then change the code inside the loop to read
$tests[] = $row['ID'];
then you can do away with the '$tests = explode(...' line.
Your having the issue with your in_array test because you are comparing an array and with a string in the following line:
if (in_array("2, 48", $tests))
The above line checks if the string "2, 48" exist in the array. But the array will have 2 as one element and 48 as a separate element. To fix this you can search for each element individually with something like:
if(in_array('2',$tests) || in_array('48',$tests))
Hey all i have a mind bug with this wile loop , i am a bit of a noob
$sql_advanced_bio = mysql_query("SELECT * FROM bio_details WHERE mem_id='$id'");
while($row = mysql_fetch_assoc($sql_advanced_bio)){
$bio_time_family = $row["bio_time_family"];
}
So this is the php now in my HTML i have this
*php echo $bio_time_family *
Why dose it echo only one value ?
SIMPLE ANSWER
so i tried somethingh easier like this $bio_fun_family .= $row["bio_fun_family"].",";
and then this
$bio_fun_family = substr($bio_fun_family,0,-1);
I added the .next to the =
It appends the values
You need to store the values in an array, otherwise you're just overwriting one variable each time, so you'll just end up with the last value.
You also need to use a loop to echo out each value in the array.
$sql_advanced_bio = mysql_query("SELECT * FROM bio_details WHERE mem_id='$id'");
$bio_time_family = array();
while($row = mysql_fetch_assoc($sql_advanced_bio)) {
$bio_time_family[] = $row["bio_time_family"];
}
And then for the output;
foreach($bio_time_family as $b) {
echo($b . '<br />');
}
With each iteration of the while loop, you're assigning to $bio_time_family the newly extracted value. If you'd like to make an array of the, instead, use $bio_time_family[] = $row["bio_time_family"];
Because every time you run through the loop you're re-assigning $bio_time_family to the next row's value. Try calling echo directly in your loop or add the row to an array, then loop through that and output the rows
ok i have this and it doesn't show all the rows when fetched from mysql database its like this:
mysql_select_db($database_config, $config);
$query_cat = "SELECT * FROM cat";
$cat = mysql_query($query_cat, $config) or die(mysql_error());
$row_cat = mysql_fetch_array($cat);
$arr = array("TIT" => $row_cat['title'],
"DES" => $row_cat['description']);
foreach($arr as $ar){
echo $ar;
}
now it only displays the first row and then stops why is it not displaying all the fields and i don't wanna use while loop for it can anyone explain me the problem??
EDIT: Well basically i want to work it like this
$p = "{TIT}{DES}";
foreach($arr as $k => $p){
$p = str_replace("{".$k."}", $v, $p);
echo $p;
}
Now the problem is not with str_replace its with the loop or database because the database rows are not incrementing and displays only one data.
This will always return the first row. you are fetching only once that will return only first row.
Instead you must fetch all the rows using fetch statement in loop
while($row_cat = mysql_fetch_array($cat)){
echo $row_cat['title'];
echo $row_cat['description'];
}
From PHP mysq_fetch_array documentation:
"Returns an array that corresponds to the fetched row and moves the internal data pointer ahead"
As far as I know, you cannot retrieve every row without using a loop. You should do something similar to this:
while($row_cat = mysql_fetch_array($cat)){
echo $row_cat['title'];
echo $row_cat['description'];
}