Laravel database insert with combining array and string - php

I should insert an array such as $attendanceList = [18354012,18354013,18354014,18354015] and $present = "FALSE" and same for all item of $attendanceList. As you see $attendanceList is array but $present is String.
When I insert like DB::table("attendance")->insert(["id"=>$attendanceList,"present"=>"FALSE"]) returns error.
What should I do? Pairing all item of $attendanceList and $present or there are another ways?
Note: I don't want to use loop if it is possible.

You can prepare array from your data and do bulk insert in one query:
<?php
$attendanceList = [18354012,18354013,18354014,18354015];
$present = "FALSE";
$insertData = array_map(
fn($el)=>['id'=>$el, 'present'=>$present],
$attendanceList
);
$db::table("attendance")->insert($insertData);
Test Laravel DB insert online

I'm not sure why you don't want to use a loop. If you want to insert four separate rows, you're going to need one:
foreach ($attendanceList as $id) {
DB::table("attendance")->insert(["id" => $id,"present" => $present]);
}

Related

How to execute two different query with single foreach in PHP

I am working with Php and right now i am inserting query using foreach loop (passing array) but how can i use another query with foreach and pass value into same array ?
Here is my current code
$data=$this->db->get($firstquery) // first query record in array
$second=$this->db->get($second_query); // second query record in array
foreach($records as $rec)
{
$data22 = array
(
'file_id'=>$rec['id'], // here is first query result
'text'=> // How to pass second query result here
);
}
You can call another loop inside main loop and execute another query
$data=$this->db->get($firstquery) // first query record in array
$second=$this->db->get($second_query); // second query record in array
foreach($records as $rec)
{
foreach($second as $sec) //second query loop
{
//enter code here
}
$data22 = array
(
'file_id'=>$rec['id'], // here is first query result
'text'=> // How to pass second query result here
);
}

Why PHP Mysql query inside a foreach loop always returns the first result from database?

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

Fetch data from mysql using associative array and implode (codeigniter + MySql)

I've gathered data from multiple MySql tables and stored them as associative arrays using a foreach loop with the query.
I would like to use those associative arrays and the implode method in the mysql query to gather more data from a separate table.
I know that with the implode method, when dealing with Indexed arrays, you can just insert the array directly in the "implode section". But with associative arrays, I am unsure how to call all the available arrays and insert them in the query.
Please refer to the attached image for a detailed illustration explaining it further.
Below is also a portion of my code
public function user_implode()
{
$s_id = array(
"id" => 383
);
$count = 0;
foreach ($query->result() as $row)
{
$count = $count + 1;
$loop_number[$count] = $row->id;
}
$this->db->from('occupation');
$this->db->where_in('id',implode("','",$loop_number[$count]));
$query = $this->db->get();
foreach ($query->result() as $row)
{
echo $row->id;
}
echo 'Total Results: ' . $query->num_rows();
}
THANKS ALOT
The second parameter to where_in() should be an array.
You are generating a string with implode() and only of the last value of the array instead of the whole array.
So all you need is:
$this->db->where_in('id', $loop_number);
And I don't see where $query comes from, it seems to be undefined when you use it in the first loop in your method.
Apart from that you should initialize your variable, $loop_number = []; before the loop.

Foreach loop, what did I do wrong?

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

php mysql data only shows one row with foreach loop

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

Categories