Foreach loop giving me this error "Warning: Illegal string offset" - php

I'm trying to print all the rows from my table I used if statement but it only return one row, so I tried to use foreach statement but it gives me an error "Warning: Illegal string offset" for each row, this is the code I'm using:
$sql = "SELECT date, km_entre, km_sortie, type, montant FROM carburant WHERE id_user = 0";
$statement = $conn->query($sql);
$res = $statement->fetch();
foreach ($res as $roww){
echo ' <tr>
<td>' .$roww['date']. '</td>
<td>' .$roww['km_entre']. '</td>
<td>' .$roww['km_sortie']. '</td>
<td>' .$roww['type']. '</td>
<td>' .$roww['montant']. '</td>
</tr>';
}
Where did I go wrong?

for everyone having the same problem check this :
Illegal string offset Warning PHP
all i had to do is changing fetch() to fetchALL(PDO::FETCH_ASSOC).

Related

All database items are appearing in each row instead of in their own

I have a form where users can order multiple parts and an email alert is sent with the data. Everything works great, but when there are multiple parts ordered each item appears multiple times. I would like to have each item appear once, on its own line.
This is the PHP that is generating the table:
$requestpartnumberarraybr = implode("<br>", $requestpartnumber);
$requestpartdescriptionarraybr = implode("<br>", $requestpartdescription);
$requestpartquantityarraybr = implode("<br>", $requestpartquantity);
$requestpartpricearraybr = implode("<br>", $requestpartprice);
$warehousearraybr = implode("<br>", $warehouse);
$binarraybr = implode("<br>", $bin);
$onhandarraybr = implode("<br>", $onhand);
$availablearraybr = implode("<br>", $available);
foreach($requestpartnumber as $key=>$val) {
$message_middle.='
<tr>
<td>' . $requestpartnumberarraybr. '</td>
<td>' . $requestpartdescriptionarraybr . '</td>
<td>' . $requestpartquantityarraybr. '</td>
<td>' . $requestpartpricearraybr . '</td>
<td>' . $warehousearraybr . '</td>
<td>' . $binarraybr . '</td>
<td>' . $onhandarraybr . '</td>
<td>' . $availablearraybr . '</td>
</tr>';
}
That code produces this - note that there are multiple items in each row, and then they are repeated:
It's supposed to look like this, though, with each item just having one row to itself:
The issue you are experiencing is that you are concatenating every value in the list, and then for each element in the list you are displaying that concatenated value.
//Here you are compressing the array of part numbers into one variable with all the values in the list
$requestpartnumberarraybr = implode("<br>", $requestpartnumber);
...
//Here you loop over each item in the array
foreach($requestpartnumber as $key=>$val) {
...
//Here, in the loop, you write the variable that has all elements in the array
'<td align="center" style="border:1px solid black!important;"><font color="black">' . $requestpartnumberarraybr. '</font></td>'
So that's why it is happening.
As for what to do instead, it seems a little unclear how your information is coming in, but you should be able to simply use $val instead of $requestpartnumberarraybr when adding to your table variable, and for the other values you should be able to use $key on their arrays, like so: $requestpartdescription[$key].

php while loop in an elseif, infinite return of first row

So i have a while loop within an if statement that is supposed to go through all of the rows in a database query and list them. however, it just returns one result (the first one) and infinitely lists it. Ive tried everything i can think of and seen and i still get infinite loops.
if($result) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$numrows = mysqli_num_rows($result);
$custNum = $row['custNum'];
$custName = $row['custName'];
$trackNum = $row['newTrack'];
$date = $row['pickUp'];
// only one result
if ( $numrows > 1 ) {
echo '
<table>
<tr>
<td>' .$custName. '</td>
</tr>';
while($row) {
echo '
<tr>
<td>' .$trackNum. '</td>
<td>' .$date. '</td>
</tr>';
};
echo '</table>';
} // end of if $numrows
} // end of if $result
You need to iterate/fetch in every loop.
Try something like this:
if($result) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$numrows = mysqli_num_rows($result);
$custNum = $row['custNum'];
$custName = $row['custName'];
// only one result
if ( $numrows > 1 ) {
echo '
<table>
<tr>
<td>' .$custName. '</td>
</tr>';
while($row) {
$trackNum = $row['newTrack'];
$date = $row['pickUp'];
echo '
<tr>
<td>' .$trackNum. '</td>
<td>' .$date. '</td>
</tr>';
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
}
echo '</table>';
} // end of if $numrows
} // end of if $result
Remember what a loop does: It executes the code from top (while(...)) to bottom (the code right before the closing bracket) and then repeats it. No other code is executed as long as you're inside the loop. Now, where is the code that fetches the data from your database? It is outside the while loop, so it won't be executed when your while loop goes on. Since you want to fetch new data in each iteration of the loop, you have to include the fetch statement inside the loop.
What Cheruvian and Philipp Murray said.
More specifically, a while process will process as long as the condition remains true. $row in your original code is established once and when set, remains set and doesn't change, thus remaining true indefinitely. This is called an infinite loop.
while ($row = mysql_fetch_assoc($result)){
// execute logic here
}
This code snippet works, because mysql_fetch_assoc iterates over a record set incrementally and returns null when it has completed all records, thus ending the while condition.

Syntax for displaying one variable in PHP of SQL query

I was practicing making some sort of phonebook for my contacts and I ran into a problem when displaying the information in a table that is dynamically created using PHP. The table displays a row for each type of phone a person posses, for example for the house, cellphone and so on.
For that I made multiple functions that get information out of a database, but then I realized that I cannot think of a way to to return just the one variable I need (the number) because my select is also taking the id of the contact and of the type of phone to retrieve the number.
So my question is: How can I write in the PHP function that I only want to display the field for the phone number (numeroTelefono).
To further illustrate here is mySQL queries and PHP functions:
PHP function that creates the HTML and display the information the query gets:
function displaySpecificTels(){
if(isset($_POST['pIdC'])){
$idC = $_POST['pIdC'];
$casa = getSpecificCasa($idC);
$movil = getSpecificMovil($idC);
$trabajo = getSpecificTrabajo($idC);
$fax = getSpecificFax($idC);
$otro = getSpecificOtro($idC);
while($row = mysql_fetch_assoc($PLACEHOLDER)){
Perhaps remove the while and just echo? If so then what do I write where $row was?
echo
'<table class="tableFormat2 floatLeft">
<thead>
<tr>
<th>Casa</th>
<th>Móvil</th>
<th>Trabajo</th>
<th>Fax</th>
<th>Otro</th>
</tr>
</thead>
<tbody>
<tr>
<td>' . $row['casa'] . '</td>
<td>' . $row['movil'] . '</td>
<td>' . $row['trabajo'] . '</td>
<td>' . $row['fax'] . '</td>
<td>' . $row['otro'] . '</td>
</tr>
</tbody>
</table>';
}
}
}
SQL example of one of my functions:
function getSpecificCasa($idCont){
$id = 1;
$query = "SELECT bk.idTelefono , bk.idTipoTelefono, bk.numeroTelefono FROM telefono as bk WHERE bk.idTipoTelefono = $id AND bk.idTelefono = $idCont";
$result = do_query($query);
return $result;
}
EDIT:
Do_Query function does this:
function do_query($query){
global $db_server;
$result = mysql_query($query , $db_server);
if( !$result)
die("Falló la sentencia" . mysql_error());
return $result;
}
Would just returning bk.numeroTelefono and then using $result in the PHP that creates the HTML be viable?

Concept Help Needed: Tables and Displaying All Rows

I have an upload system in my site where users can upload files and write a brief description of them. Each upload has a corresponding SQL entry.
Another page on my site will then display every file uploaded along with some traits about that file
The question is:
How can create a table with a variable set of rows and how can I set a table to automatically populate the new rows?
I am capable with PHP but still a novice, weak with HTML (I use a wysiwyg) and completely inexperienced with Javascript.
Any nudge in the correct direction would be hugely appreciated...
In order to make the rows of your HTML table "dynamic" using PHP, you should use the foreach() control structure. For example, say you have some code to grab the data from the database and it returns it as an array or some sort of result statement that implements an Iterable interface (we'll call it $results), you can then:
<table>
<thead>
<tr>
<th>File Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
foreach($results as $result)
{
// Start row
echo("<tr>");
echo("<td>" . $result->filename . "</td>");
echo("<td>" . $result->description . "</td>");
// End row
echo("</tr>");
}
?>
</tbody>
</table>
You can use a loop to populate the table based on results from a query of your database. Here's the code I use for one of my pages:
$result = $db->query_read("SELECT dice.RollID AS `Roll`, dice.Limit AS `Limit`,
dice.Value AS `Value`, dice.Dateline AS `Dateline`, dice.Comment AS `Comment`
FROM dice
ORDER BY Dateline DESC LIMIT 25");
// ###### MAIN CODE ######
$str = '<table>
<tr><th>ID</th><th>Roll</th><th>Time</th><th>Comment</th></tr>';
while ($resultLoop = $db->fetch_array($result)) {
$ID = $resultLoop["Roll"];
$roll = $resultLoop["Value"] . '/' . $resultLoop["Limit"];
$when = date('m-d-Y H:i:s', $resultLoop["Dateline"]);
$comment = $resultLoop["Comment"];
$str .= '<tr>
<td>' . $ID . '</td>
<td>' . $roll . '</td>
<td>' . $when . '</td>
<td>' . $comment . '</td></tr>';
}
$str .= '</table>';
echo $str;
One thing to note is that I use $db->* functions because it is integrated with a forum software. You should be using mysqli_* functions as found here: http://php.net/manual/en/book.mysqli.php

Only one result showing after sql request and while loop

For some reason this only shows the last result, instead of showing all. The SQL works in the workbench, and $roommate is escaped, but the code has been trimmed for posting purposes:
$sql = "SELECT CONCAT(clients.studentFirstName, ' ', clients.studentLastName) AS name, appointments.location, appointments.subLocation, appointments.startTime, appointments.endTime, appointments.date
FROM appointments JOIN clients
ON appointments.clientID = clients.clientID
WHERE CONCAT(clients.studentFirstName, ' ', clients.studentLastName) = '".$roommate."';";
while ($row = mysql_fetch_array($result)) {
echo
'<table>
<tr>
<td>'
.$row["name"].
'</td>
<td>'
.$row["location"].
'</td>
<td>'
.$row["subLocation"].
'</td>
</tr>
<tr>
<td>'
.$row["startTime"].
' - </td>
<td>'
.$row["endTime"].
'</td>
<td>'
.$row["date"].
'</td>
</tr>
</table>';
}
Use mysql_num_rows() to determine the number of rows that were returned by your query. If it reports that you are only getting 1 result, then you will need to refine your query to get the number of results you intend.
If you're using one of the mysql_fetch_* functions before the while loop, that would advance the cursor and make you miss one or more results in your while loop. If that's the case, call mysql_data_seek($result, 0) before the while loop.

Categories