I have a loop like this (just a sample, many vars are missing):
foreach($inserts as $insert) {
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIDs[] = array($tables[$tbl]['owner'] => $insert_update);
}
Now as you see $insertedIDs[] is getting in the array all the new inserted IDs.
The problem is that on the next $inserts loop I'll need that $insertedIDs[] to be available for other variables of the loop, that will need to get the last inserted ID.
The problem is that on the next loop this variable is not recognized and it returns errors.
How can I make $insertedIDs[] available on each next loop after the first loop?
I tried declaring $insertedIDs[] as global just after the foreach but no luck.
Try this may be it'll help you:
$insertedIDs=Array();
foreach($inserts as $insert) {
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIDs[] = array($tables[$tbl]['owner'] => $insert_update);
}
Now you are able to access $insertedIDs
$insertedIDs = array();
foreach($inserts as $insert) {
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIDs[ $tables[$tbl]['owner'] ] = $insert_update;
}
print_r($insertedIDs);
Pretty easy actually... Try not to over-think it.
//create an empty array
var $insertedIds = array();
//now loop and add to the array
foreach( $inserts as $insert )
{
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIds[][$tables[$tbl]['owner']] = $insert_update;
//or if you want the owners to be keys in the first level of the array...
//$insertedIds[$tables[$tbl]['owner']] = $insert_update;
}
//output the contents of the array
echo '<pre>' . print_r($insertedIds, true) . '</pre>';
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/>';
}
}
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);
$sql = mysql_query("SELECT * FROM table WHERE user='$user'" );
while($data=mysql_fetch_array($sql)){
echo $data['user']; //this is fine
}
echo $data['user'];
$data=mysql_fetch_array($sql);
echo $data['user'];
The last two echos are empty?
I need to have an array outside of the loop that is equivalent to the 'last' loop cycle.
The while loop keeps fetching data, until there is no more data and therefore false is returned by mysql_fetch_array. This last value, false, is still in $data after the loop has ended, but simply printing it using echo, won't print anything you can see. The same goes for the next call of mysql_fetch_array and echo. You can check this by doing a var_dump of the $data variable. This will show you that it contains the boolean false.
If you want to be able to use the data after the loop has ended, you can save all the data you fetch into one big array. That might be a bad option though if you're fetching a lot of data, but from there you should be able to change it yourself so you can save and use the useful data. To store all the data in an array, change the loop into this:
$alldata = array();
while($data=mysql_fetch_array($sql))
{
echo $data['user'];
$alldata[] = $data;
}
You can then for example iterate over $alldata to go over the results again.
Update: In your last comment you said you want to access the last record that was fetched. You can do that like this:
$lastdata = array();
while($data=mysql_fetch_array($sql))
{
echo $data['user'];
$lastdata = $data;
}
$lastdata will then contain the last record in your result.
Because of the following:
while($data = mysql_fetch_array($sql)) {
// mysql_fetch_array returned something 'not false' and this value
// is assigned to $daat
}
// mysql_fetch_array() returned false, because there are no more rows
// false is assigned to $data, and because the statement within while(...)
// isn't true anymore the loop is stopped.
Use
$data = mysql_fetch_array($sql);
if (!$data) {
echo "User don't exists";
}
for example to handle this situation
I have searched for similar questions but cannot find the right answer to my specific one. I have a column (data) in my table (table) which contains comma separated values which are id's e.g.
Row 1= 4,5,45
Row 2= 5,8,9
Row 3= 5
I use an in_array function to retrieve the number of occurances for the $data value within the while loop. So I use an sql function to retrieve the number of times a certain value such as '5' occurs in all rows within the while loop.
The issue is that I can only retrieve the $data value if it is by itself (i.e. no commas just the integer by itself) so based on my example in the list, I can only retrieve 5 once (row 3). I would like to retrieve the value '5' three times as it appears in all the rows. Here is my code below and any help would be appreciated. The $selectiontext variable is what the user enters from the form.
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
}
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
Thank you.
you keep overwriting the variables $datacheck and $id, leaving you with only the last version of them. move that curly brace down two lines, like this:
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
}
I am not totally sure of your requirements, is not very clear what you intend to do as part of the code is missing.
I assume you want to check each row of a comma separated of a CSV file ($frnd_arry_mem1 being the row) against your data in column data, if any of those comma separated data (not) occurs.
Assuming you are already looping through your CSV, this would be the code (non tested):
NOTE: might be inefficient retrieving data within a loop, if you can do otherwise - but I cant tell as I dont kow the full specs of your script.
If I got the specs wrong please clarify, I will try to help further.
$sql = "SELECT data, id
FROM table
WHERE data='$selectiontext'";
$sql_frnd_arry_mem1 = mysql_query($sql);
$results = array();
// get values to check
while ($row = mysql_fetch_array($sql_frnd_arry_mem1))
{
$results[] = array(
'datacheck' => $row["data"],
'id' => $row["id"],
);
}
foreach ($results as $result)
{
$frndArryMem1 = explode(",", $frnd_arry_mem1);
$data = explode(',', $result['datacheck']);
foreach ($data as $d)
{
if (($frnd_arry_mem1 !=="") && (!in_array($d, $frndArryMem1)))
{
echo 'DEBUG: Record #' . $id . ' not found, value:' . $d . '</br>';
}
}
}
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'];
}