PHP Undefined index when attempting to access key in array that exists - php

I have a number of rows (ingredients) in a table in my database, I'm using the following code to iterate and populate my view with the name of each, but I want to be able to display the children/parents (columns in the DB) of each item, I'm able to log out the values correctly but when I try to echo as below I'm receiving "Message: Undefined index: parents" & "Message: Undefined index: children";
<?php foreach ($ingredient as $row => $key) { ?>
<tr>
<td><?php echo $row + 1; ?> </td>
<td><?php echo $key['name']; ?> </td>
<?php ChromePhp::log($key['parents']); ?>
<td><?php echo $key['parents']; ?> </td>
<?php ChromePhp::log($key['children']); ?>
<td><?php echo $key['children']; ?> </td>
<td>
</tr>
<?php } ?>
I'm confused as I have no issue logging it out.
I assumed it may be due to null values so I assigned child/parent a string value for each row as follows;
but the error persists.
Here is the logged output in the browser;
Output of <?php ChromePhp::log($key); ?>
EDIT: Here is how I'm building the $ingredients array;
<?php
function get_ingredient()
{
$qry = "SELECT CONCAT(UPPER(LEFT(i.name, 1)), LCASE(SUBSTRING(`name`, 2))) as name,i.id as id,'ingredient' as type, i.parents as parents, i.children as children FROM `ingredient` i WHERE i.is_del=0 order by i.name asc";
$qry = $this->db->query($qry);
if ($qry->num_rows() > 0) {
$ingr = $qry->result_array();
} else {
$ingr = array();
}
}
?>
I assume I'm missing something fundamental, any advise would be most appreciated. Cheers.

My array had two sets of data, I have resolved this by limiting the array to one set.

<?php foreach ($ingredient as $row => $key) { ?>
<tr>
<td><?php echo $row + 1; ?> </td>
<?php if(isset($key['name']) && !empty($key['name'])):?>
<td><?php echo $key['name']; ?> </td>
<?php endif;?>
<?php if(isset($key['parents']) && !empty($key['parents'])):?>
<?php ChromePhp::log($key['parents']); ?>
<td><?php echo $key['parents']; ?> </td>
<?php endif;?>
<?php if(isset($key['children']) && !empty($key['children'])):?>
<?php ChromePhp::log($key['children']); ?>
<td><?php echo $key['children']; ?> </td>
<?php endif;?>
</tr>

$key looks like an object so you have to access it with -> so to get value of name use $key->name,$key->parents

Related

How to show same id data in single row in codeigniter?

public function get_orderProduct($loginuserID) {
$this->db->select('client_order.*,product.image_gallery,product.name');
$this->db->from('client_order');
$this->db->join('product','client_order.productID = product.productID','LEFT');
$this->db->where('client_order.clientID',$loginuserID);
$this->db->where('client_order.status',1);
$this->db->order_by('client_order.id','desc');
$sql = $this->db->get();
$result = $sql->result();
return $result;
}
<?php
if(count($result) > 0){
$i=1;
foreach($result as $row){
$img = explode(",", $row->image_gallery);
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row->orderID; ?></td>
<td><?php echo $row->name; ?></td>
</tr>
<?php
$i++;
}
}else{
?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
No order available!
</div>
<?php
}
?>
I have two product with same orderID and I want to show same orderID product in single row. Now, Here it show in different different row. So, How can I show in single row? Please help me.
Thank You
To solve this, you have to create an empty array to store orderids.Before you print the orderid you have to search the array using in_array method, if orderid exists ignore printing it, otherwise print and push the orderID to the array using array_push method.
<?php
$ids = array();
$i=1;
foreach($result as $row){
$img = explode(",", $row->image_gallery);
?>
<tr>
<td><?php echo $i; ?></td>
<td>
<?php
if(!in_array($row->orderID,$ids))
{
echo $row->orderID;
array_push($ids,$row->orderID);
}
?>
</td>
<td><?php echo $row->name; ?></td>
</tr>
<?php
$i++;
}
?>

Display some html if mysqli_fetch_assoc is empty while loop php [duplicate]

This question already has answers here:
Checking if mysqli_query returned any values?
(2 answers)
Closed 3 months ago.
I'm using while loop to fetch data from the database I want to display like nothing found the result is null or empty. I've tried using if/else with like: if (empty($jobs)) echo 'nothing found'; that doesn't work. if(!mysqli_fetch_assoc($jobs)) works but if don't show the jobs if available.
Loop
<?php while ($job = mysqli_fetch_assoc($jobs)) { ?>
<tr class="custom-table-body-titles">
<td><?php echo h($job['updated_at']); ?></td>
<td>
<?php echo h($job['title']); ?>
</td>
<td>0/<?php echo h($job['required_freelancers']); ?></td>
<td><?php echo h($job['delivery_time']); ?> Days</td>
<td>$<?php echo h($job['budget']); ?></td>
<td>
Apply
</td>
</tr>
<?php } ?>
You have to do a validation to check if any results were found before even starting the loop. Assuming $jobs is an instance of mysqli_result returned by mysqli_query().
if (mysqli_num_rows($jobs) > 0)
{
// your while loop
}
else
{
echo "no jobs found";
}
You should keep PHP and HTML separate as much as you can.
You can fetch all results into an array before and then foreach on that array.
$jobs = $jobs->fetch_all(MYSQLI_ASSOC);
if($jobs) {
foreach ($jobs as $job) {
}
} else {
}
A good question which is sadly most of time is answered incorrectly.
It's a very bad practice to mix the database-related code and HTML code. There should never be a while loop like this.
Instead, the data should be fetched into array,
$jobs = [];
while ($row = mysqli_fetch_assoc($result)) {
$jobs[] = $row;
}
which is then used to output the data. And once you have this array, you can use it to tell whether the query returned any data or not:
<?php if ($jobs) { ?>
<?php foreach ($jobs as $job) { ?>
<tr class="custom-table-body-titles">
<td><?php echo h($job['updated_at']); ?></td>
<td>
<?php echo h($job['title']); ?>
</td>
<td>0/<?php echo h($job['required_freelancers']); ?></td>
<td><?php echo h($job['delivery_time']); ?> Days</td>
<td>$<?php echo h($job['budget']); ?></td>
<td>
Apply
</td>
</tr>
<?php } ?>
<?php } else {?>
no data
<?php } ?>

Mysql returns duplicate in html table

I am trying to populate html table with data from mysql.But i am stuck on this part where each time i add some data it keeps repeating. On the picture below you can see that Test 1 repeat each time for every P20,P21,P24,P22,P23 and i needed to be one TEST1 for all of them. When i add Test 2 with value 19000 its making new P20 and all data come from Test 1 to Test 2. Can someone help me how to fix this.Any hint or suggestion wil be appreciated. Thank you all very much (Sorry for my bad english)
This is code that runs this
$sql = 'SELECT DISTINCT Pers.naam, Rol.funkcija,pdata.broj
FROM ids
left JOIN Pers ON ids.persid = Pers.id
left JOIN Rol ON ids.rolid = Rol.id
left JOIN pdata ON ids.pdataid = pdata.id
';
$query = $conn->prepare($sql);
$query->execute();
$testing = $query->fetchAll(PDO::FETCH_ASSOC);
?>
<table>
<tr>
<th>P Small <small>(NONE)</small></th>
<?php
foreach ($testing as $test):
?>
<th>
<?php
echo $test['naam'] . '<br />';
?>
</th>
<?php
endforeach;
?>
</tr>
<tr>
<th>TESTING LINES</th>
</tr>
<?php foreach ($testing as $test): ?>
<tr>
<td><?php echo $test['funkcija']; ?></td>
<?php endforeach; ?>
<?php
foreach ($testing as $test):
?>
<td><?php echo $test['broj']; ?></td>
<?php
endforeach;
?>
</tr>
</table>
I would like to have it like this
There is some refactoring required to get to the output you want.
You seem to be enumerating quite a lot of data from your SQL result, so there is some grouping required to make things easier.
To get the appropriate number to each "naam" and "funkcija" you can use array_filter which however could theoretically return several numbers in each case.
You'll also have to nest a couple foreach instead of running them after one another.
If I understand your data structure correctly, this should at least give you a good starting point for the output you want:
<?php
// ...
$testing = $query->fetchAll(PDO::FETCH_ASSOC);
$naams = array_unique(array_column($testing, "naam"));
$funkcijas = array_unique(array_column($testing, "funkcija"));
?>
<table>
<tr>
<th>P Small <small>(NONE)</small></th>
<?php foreach ($naams as $naam): ?>
<th>
<?php echo $naam; ?>
</th>
<?php endforeach; ?>
</tr>
<tr>
<th>TESTING LINES</th>
</tr>
<?php foreach ($funkcijas as $funkcija): ?>
<tr>
<td><?php echo $funkcija; ?></td>
<?php foreach ($naams as $naam): ?>
<?php
$data = array_filter(
$testing,
function ($v) use ($naam, $funkcija)
{
return $v["naam"] === $naam && $v["funkcija"] === $funkcija;
}
);
foreach ($data as $value): ?>
<td><?php echo $value["broj"]; ?></td>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

Can't get the value of a data PHP

im having trouble getting a result value of a query and the error says.
Notice: Undefined index: prelim in C:\xampp\htdocs\gradingxworking\teacher\student.php on line 85 can someone help me to fix this or some clue to fix this? im just starting to learn php.
<tbody>
<?php $c=1; ?>
<?php foreach($mystudent as $row): ?>
<tr>
<td><?php echo $c; ?></td>
<td class="text-center"><?php echo $row['studid']; ?></td>
<td class="text-center"><?php echo $row['lname'].', '.$row['fname']; ?></td>
<?php $grade = $student->getstudentgrade($row['studid']);?>
//code that cause error line 85--> <td class="text-center"><?php echo $grade['prelim']; ?></td>
</tr>
<?php $c++; ?>
<?php endforeach; ?>
<?php if(!$mystudent): ?>
<tr><td colspan="8" class="text-center text-danger"><strong>*** No Result ***</strong></td></tr>
<?php endif; ?>
</tbody>
the function:
function getstudentgrade($studid){
$q = "select * from studentsubject where studid=$studid";
$r = mysql_query($q);
$data = array();
while($row = mysql_fetch_array($r)){
$data[] = array(
'prelim' => $row['prelim']
);
}
return $data;
}
As #Bara suggested, you need to check the array first before accessing it.
if(isset($grade['prelim']))
I suspect, there is no data for specific studid. Lets see you function.
$data = array();
while($row = mysql_fetch_array($r)){
$data[] = array(
'prelim' => $row['prelim']
);
}
Now, you have created new array $data. But, if there is no record ? your while loop won't be executed and your $data array won't have anything. right ? So, to handle that, you need to check whether there is any data in your array.
Now, second point, which #Mossavari made is also correct. You need to use
$grade[0]['prelim'];
instead of
$grade['prelim'];
after doing
<?php $grade = $student->getstudentgrade($row['studid']);?>
you need to check what $grade holdes. and its better before trying to fetch data from array to make a check like this :
if(isset($grade['prelim']))
Based on your getstudentgrade function you'll have multidimensional array result, you may need to change $grade['prelim'] to $grade[0]['prelim']
Since, every student will have only 1 grade. So, why to use array.
<?php
function getstudentgrade($studid){
$q = "select * from studentsubject where studid=$studid LIMIT 0,1";
$data = "";
$r = mysql_query($q);
while($row = mysql_fetch_array($r)){
$data = $row['prelim'];
}
return $data;
}?>
PHP
<tbody>
<?php $c=1; ?>
<?php foreach($mystudent as $row): ?>
<tr>
<td><?php echo $c; ?></td>
<td class="text-center"><?php echo $row['studid']; ?></td>
<td class="text-center"><?php echo $row['lname'].', '.$row['fname']; ?></td>
<td class="text-center"><?php echo $grade = $student->getstudentgrade($row['studid']);?></td>
</tr>
<?php $c++; ?>
<?php endforeach; ?>
<?php if(!$mystudent): ?>
<tr>
<td colspan="8" class="text-center text-danger">
<strong>*** No Result ***</strong>
</td>
</tr>
<?php endif; ?>
</tbody>

For loop inside Foreach

I got a foreach which loops through my database for each user.
<?php
foreach($users as $user) {
?>
<tr>
<td>
<?php
for ($i=1; $i < 52; $i++) {
echo $i;
}
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
This loop through database and echos the username, now I tried to build a for loop inside this so that every user has a number, I took as an example a very basic for loop ( it will be changed later).
The problem is that I get all numbers printed out for each user, but I just want to print out the number once for a user. How do I solve this.
If you want unique index number for user, you do not need extra loop.
Just add an increment variable:
And increment it in existing loop.
<?php
$i=0;
foreach($users as $user) {
++$i; // For printing first user, it will be 1 not 0.
// Therefore, increment is placed before printing name.
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php
}
?>
This should be enough to achieve what you're trying to do :
Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it.
Also you should avoid to open your php tags ten thousands times for a better visibility into your code :)
<?php
$i = 0;
foreach($users as $user) {
$i++;
echo'<tr>
<td>'.$i.'</td>
<td>'.$user['firstname'].'</td>
</tr>';
?>
<?php
$i=1;
foreach($users as $user) {
?>
<tr>
<td>
<?php
echo $i++;
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
Try to use the key in foreach
<?php foreach ($users as $key => $user) : ?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php endforeach; ?>

Categories