Show DB In Array Using Foreach Loop - php

I'm trying to use foreach loop, for showing my DB but I always get error. What I want is to print each row and column. My code is like this :
$sql = "SELECT a.*, b.klasifikasi FROM kl_stre as b
INNER JOIN data_latih as a
ON a.id_stres = b.id_stres
ORDER BY a.id_dl";
$result = mysqli_query($conn, $sql);
foreach ($result as $dt_train => $row_dt_train):
foreach ($row_dt_train as $attr => $attr_dt_train):
echo $result[$row_dt_train][$attr_dt_trian]; // this line is the problem
endforeach;
endforeach;
the error I get is
Warning: Illegal offset type in C:\xampp\htdocs\knn\array_db.php on line 43
Would you mind explaining what is wrong with this code and how to solve this problem ?

you need to first check your query
if (!$result) {
die('query is not correct'.mysqli_error($conn));//$con is your database connection paste it after $result = mysqli_query($conn, $sql);
}
after that fetch record and simply remove foreach and try to use while() loop
while ($row=mysqli_fetch_array($result)) {
echo $row['your database field name'];
}
your code will be
$sql = "SELECT a.*, b.klasifikasi FROM kl_stre as b
INNER JOIN data_latih as a
ON a.id_stres = b.id_stres
ORDER BY a.id_dl";
$result = mysqli_query($conn, $sql);
if (!$result) {
die('query is not correct'.mysqli_error($conn));
}
while ($row=mysqli_fetch_array($result)) {
echo $row['your database field name'];
}

Related

Query specific columns from database table to json

I'm trying to get specific columns from a database table rather than selecting the whole table and put them to json format. There's no need for irrelevant columns. This is what i have so far.
$sql = "SELECT (col1,col2,col3) FROM table1";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
mysqli_close($connection);
This code returns with an error: Operand should contain 1 column(s)
Any ideas what I'm doing wrong?
Thanks
The error is with the query. You are selecting 3 columns but putting them in brackets () would project them as single column. Try -
SELECT col1,col2,col3 FROM table1
You can refer to this answer for details.
You have to specify column name when access query result.
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$sql = "SELECT col1,col2,col3 FROM table1";
$emparray = array();
$index = 0;
while($row =mysqli_fetch_assoc($result))
{
$emparray[$index][] = $row['col1'];
$emparray[$index][] = $row['col2'];
$emparray[$index][] = $row['col3'];
$index++;
}
echo json_encode($emparray);
mysqli_close($connection);

Problems getting my info from table join to display in PHP

{Connecting 2 tables together (with teacher ID and teacher name)
I have created the join and I have tested in SQL. Seems good. I am trying to print it on the screen.
$classandteacher = "SELECT person_name FROM people RIGHT OUTER JOIN classes ON classes.instructor_id=people.instructor_id ASC";
$result = mysqli_query($dbc, $classandteacher){
while($row = mysqli_query($dbc, $result));
$teacher = $row["person_name"];
echo ("Teacher: " . $teacher . "<br>");}
It's because the While Loop isn't correctly formatted.
Remove the ; and put it into {}
You also need to use mysqli_fetch_assoc($result) to get the Array from the query
$classandteacher = "SELECT person_name FROM people RIGHT OUTER JOIN classes ON classes.instructor_id=people.instructor_id ASC";
$result = mysqli_query($dbc, $classandteacher);
if(!$result) { //If your MYSQL query is throwing an error
error_log(mysqli_error());
}
while($row = mysqli_fetch_assoc($result))
{
$teacher = $row["person_name"];
echo "Teacher: " . $teacher . "<br>";
}
Or try using
mysqli_fetch_array instead
$classandteacher =
"SELECT
person_name FROM
people RIGHT OUTER JOIN classes ON
classes.instructor_id
=
peopleinstructor_id ASC";
$result =
mysqli_query($dbc,$ classandteacher);
if(!$result) { //If
your MYSQL query is
throwing an error
error_log(mysqli_er
ror() );}
while($row =
mysqli_fetch_array(
$result))
{
$teacher = $row
["person_name"];
echo "Teacher: " . $
teacher . "<br>"; }

Error displaying rows from MySQL tables

I am trying to get rows from a table when a condition is satisfied (status = 'no transit') but nothing shows up even when rows are supposed to show up (count is 1 and more).
if($query['num'] == 0){
echo "<p>No shopping orders on transit</p>";
}else{
$sql = "SELECT *, FORMAT(total, 0) AS total, FORMAT(grand_total, 0) AS grand_total FROM shipping_details WHERE status = 'no transit' ORDER BY order_id DESC";
foreach ($db->query($sql) AS $query){
echo" Show some results ";
$select = "SELECT * FROM shipping_order WHERE order_id = :order_id";
foreach ($db->query($select, array('order_id' => $query['order_id'])) AS $items){
echo"
Some results
";
//Foreach ends
}
}
}
You don't show enough that we can tell which codebase you use to connect to your DB (MySQLi, mysql_, or PDO), so the code below may need some tweaking.
The problem is basically that you never retrieve your database results. Instead you try to loop through the query execution itself.
Change
$sql = "SELECT *...";
foreach ($db->query($sql) AS $query)...
To
$sql = "SELECT *...";
$result = $db->query($sql); //execute the query
if(!$result) die($db->error); //exit and show error if query failed
//now we can fetch the results one at a time and loop through them
//this line may need to be adjusted if you're not using MySQLi
while($row = $result->fetch_assoc())...
Within the while loop, $row will contain the values from the DB record. Use print_r($row) to learn its shape.
It is not working, because you forgot to use prepare and execute methods from pdoStatemnt class.
See below:
$stmt = $db->prepare("SELECT * FROM shipping_order WHERE order_id = :order_id");
$stmt->execute(array('order_id' => $query['order_id']));
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)){
echo"
Some results
";
//Foreach ends
}

PHP & MYSQLI selecting MySQL Table for Shop Items

For my school I need to Select items from the MySQL Server and it only should show the name and the price.
$sql = "SELECT `item`,`price` FROM `items` ";
$query = mysqli_query(con(), $sql);
$row = mysqli_fetch_array($query);
foreach($row as $values)
{
echo "<p>".$values["item"]."</p>";
echo "<p>".$values["price"]."</p>";
}
I only got something like:
L
L
L
L
4
4
4
4
Its the only first item in the table but there are many rows in DB.
you're doing fine, but what you're doing wrong is, you're picking just one item and iterating over that single value.
Here you're extracting only LLLL4444 and looping on this only, so, in order to get all.
You need to do this.
$sql = "SELECT `item`,`price` FROM `items` ";
$query = mysqli_query(con(), $sql);
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row["item"]."</p>";
echo "<p>".$row["price"]."</p>";
}
Try this:
$sql = "SELECT `item`,`price` FROM `items` ";
$query = mysqli_query(con(), $sql);
while ($row = mysqli_fetch_assoc($query)) {
echo "<p>".$row["item"]."</p>";
echo "<p>".$row["price"]."</p>";
}
mysql_fetch_array() essentially returns two arrays one with numeric index, one with associative string index.
So using mysql_fetch_array() without specifying MYSQL_ASSOC or MYSQL_NUM, or by specifying MYSQL_BOTH will return two arrays

Getting number of rows form SQL Server table

I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.

Categories