How to run two statements in mysqli_query - php

I need to run two statements to return the data I need. The below code will return all needed except the count column which can be retrieved from a different table.
How can I run these two statements in the same code to retrieve the count as well?
Here is the code I have:
<?php
$query = "SELECT * from $CLIENTS_DATABASE order by id DESC";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo $row["name"]; ?> </td>
<td><?php echo $row["url"]; ?> </td>
<td><?php echo $row["secret"]; ?> </td>
<td><?php echo $row["count"]; ?> </td>
</tr>
<?php
}
mysqli_free_result($result);
}
?>
The other statement that the count data I need is this:
$query = "SELECT COUNT(*) as count from visits where id_client='$result[id]'"
Thanks for your time and any help you can provide.

Join the two queries.
$query = "SELECT order.*, IFNULL(c.count, 0) AS count
FROM $CLIENTS_DATABASE AS order
LEFT JOIN (SELECT id_client, COUNT(*) AS count
FROM visits
GROUP BY id_client) AS c
ON c.id_client = order.id
ORDER BY order.id DESC";

Related

Displaying SQL Query in HTML table (php)

Trying to get counts from 2 different tables into a simple HTML table.
This is my code:
$sql = "SELECT COUNT(*) FROM tasks";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
if ($result->num_rows > 0) { ?>
<table style="width:100%">
<tr>
<th>Total</th>
</tr>
<?php while($row = $result->fetch_assoc()) { ?>
<tr>
<td><?=$rowcount;?></td>
</tr>
<?php } ?>
</table>
<?php } else { echo "0 results"; } ?>
When I run the code, it shows the amount of rows in the table, but it also creates the amount of rows with the number in it (i.e. 281 rows).
Table
281
281
281
281 etc.
My idea was to copy and paste the above to show a second table set of results (if it was correct), but is there a better way of doing this? I've been looking at how I would display SELECT (select COUNT(*) from tasks) , (select count(*) from quotes) into the following format (HTML):
Table
Count
Tasks
281
Quotes
42000
First of all your query does produces only one row for a table, not 281.
The second - I omit usage of prepared SQL statements with placeholders, which should always be used in a real project whenever applyable.
$rows = [];
foreach(['Tasks', 'Quotes'] as $table ){
$result = $conn->query("SELECT '$table' as 'table', count(*) as 'count' FROM $table");
if( $result )
$rows[] = $result->fetch_assoc();
}
if( empty( $rows ) )
print "0 results";
else {?>
<table style="width:100%">
<tr><th>Table</th><th>Count</th></tr>
<?=implode(
"\n",
array_map(function($row){
return "<tr><td>${row['table']}</td><td>${row['count']}</td></tr>";
}, $rows)
)?>
</table>
<?php }
I've been looking at how I would display SELECT (select COUNT() from
tasks) , (select count() from quotes) into the following format
(HTML)
You can just run the queries query, and use the result of the first to create the first row of the table, then the result of the second to create the second row. Since COUNT queries always return exactly 1 row when there's no GROUP BY, it's quite simple to do really:
$sql1 = "SELECT COUNT(*) FROM tasks";
$result1 = $conn->query($sql1);
if ($row = $result1->fetch_array()) $taskCount = $row[0];
else $taskCount = "error";
$sql2 = "SELECT COUNT(*) FROM quotes";
$result2 = $conn->query($sql2);
if ($row = $result2->fetch_array()) $quoteCount = $row[0];
else $quoteCount = "error";
?>
<table style="width:100%">
<tr>
<th>Table</th>
<th>Count</th>
</tr>
<tr>
<td>Tasks</td>
<td><?php echo $taskCount; ?></td>
</tr>
<tr>
<td>Quotes</td>
<td><?php echo $quoteCount; ?></td>
</tr>
</table>
Another way, if you want the HTML structure to be less repetitive / dependent on the tables queries, is to UNION the SELECTs into a single query:
$sql = "SELECT 'Tasks' AS 'table', COUNT(*) as 'count' FROM tasks";
$sql .= " UNION ";
$sql .= "SELECT 'Quotes' AS 'table', COUNT(*) as 'count' FROM quotes";
$result = $conn->query($sql);
?>
<table style="width:100%">
<tr>
<th>Table</th>
<th>Count</th>
</tr>
<?php
while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo $row["table"]; ?></td>
<td><?php echo $row["count"]; ?></td>
</tr>
<?php
}
?>
</table>

How do I display item title from 1 category (tbl_category) in a table that represents another category?

I have 2 tables tbl_category and tbl_food.
I sorted the items from tbl_food to tbl_category by adding category_id to tbl_food, where category_id in tbl_food is identical to id in tbl_category.
But how do I take title from tbl_category and display it in a table that represents items from tbl_food?
<?php
//query to get all admin from dtb
$sql = "SELECT * FROM tbl_food";
//Exectue the query
$res = mysqli_query($conn, $sql);
//check if executed
if($res==TRUE)
{
//count rows to check wether we have data
$count = mysqli_num_rows($res); //get all rows in dtb
$sn=1; //create a variable and assign the value
//check numb of rows
if($count>0)
{
//there is data
while($rows=mysqli_fetch_assoc($res))
{
//using while loop to get data from dtb
//get individual data
$id=$rows['id'];
$title=$rows['title'];
$description=$rows['description'];
$price=$rows['price'];
$active=$rows['active'];
$category_id=$rows['category_id'];
//display values in table
?>
<tr>
<td><?php echo $sn++; ?></td>
<td><?php echo $title; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $price; ?> kn</td>
<td><?php echo $active; ?></td>
<td><?php echo $category_id; ?></td>
</tr>
<?php
}}
else{
?>
<tr colspan="4">
<td class="error">No categories added</td>
</tr>
<?php
}
}
?>
I think you need to edit your query by adding JOIN to join tbl_category to tbl_food via category_id, at first, like this:
$sql = "SELECT food.*, category.title FROM tbl_food AS food INNER JOIN tbl_category AS category ON category.id=food.category_id";
Secondly it seems you have mistake in iterating query results. mysqli_fetch_assoc($res) returns an associated array, so it must be like this:
$rows = mysqli_fetch_assoc($res)
foreach($rows as $row){
$id=$row['id'];
$title=$row['title'];
$description=$row['description'];
$price=$row['price'];
$active=$row['active'];
$category_id=$row['category_id'];
//Doing stuff
}
You have to method for get title from tbl_category
1- JOIN Method: it is already mentioned above
2- Condition Method:
$sql = "SELECT tbl_food.*, tbl_category.title FROM tbl_food,tbl_category WHERE tbl_category.id=tbl_food.category_id";
foreach($sql as $row){
$id=$row['id'];
$title=$row['title'];
$description=$row['description'];
$price=$row['price'];
$active=$row['active'];
$category_id=$row['category_id'];
}

paginate through records with php and mssql server

i just moved to asp and php and i'm able to connect to mssql database and retrieve records. what i'm currenlty finding it hard to do is how to do pagination through the records showing 10 records at a time.
<table width="40%" border="1" align="center" cellpadding="5" cellspacing="5">
<tr>
<td>Item-</td>
<td>Quantity</td>
<td>Price</td>
</tr>
<?php
while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {
?>
<tr>
<td> <?php echo $row['item'] ?></td>
<td><?php echo $row['quantity'] ?></td>
<td><?php echo $row['rprice'] ?></td>
</tr>
<?php
}
?>
<tr>
<td><div align="left">Previous</div></td>
<td> </td>
<td><div align="right">Next</div></td>
</tr>
</table>
PHP SCRIPT
<?php require_once('Connections/db.php'); ?>
<?php
$sql = "SELECT * FROM item_table order by item desc";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $stmt );
if ($row_count === false)
echo "Error in retrieveing row count.";
else
echo $row_count;
?>
You can use OFFSET to get specific results:
$startingRow = 5;
$rowsPerPage = 10;
SELECT * FROM item_table order by item desc
OFFSET $startingRow ROWS FETCH NEXT $rowsPerPage ROWS ONLY
You will get results from 5th to 15th
If you want to do the paging in SQL Server, you can use the ROW_NUMBER function to order your rows & specify a starting point in the WHERE clause, and number of records in the TOP clause.
See the examples below. I prefer the CTE syntax.
--inline syntax
select top(10) * from (select row_number() over(order by item) as rid, * from item_table) as d where rid>10;
--cte syntax
with _numberedData as
(
select
row_number() over(order by item) as rid,
*
from item_table
)
select top(10)
*
from _numberedData
where rid>10;

Fetching Specific Orders

This is the query I have written to fetch the records from 3 different tables and display them in one simple table.
$order_id=$_REQUEST['a'];
$query="select DISTINCT product.productId,orders.id,retailerName, total, status, delivery,shopName,ownerName,address,email,contact,notes,order_item.quantity,order_item.date,productName,price,product.detail,product.price,product.expiry from orders,checkout,order_item,product where product.productId=order_item.productId and orders.id ='".$order_id."' and orders.id=order_item.orderId and orders.id=checkout.orderId";
$res=mysqli_query($conn,$query);
$row=mysqli_fetch_array($res);
The below code is written for display of record and detail.
<?PHP
while($row=mysqli_fetch_array($res)){
?>
<tr>
<?php
$subtotal=0;
$subtotal = $row['quantity'] * $row['price'];
$total += $subtotal;
?>
<td><?php echo $row['productName'];?></td>
<td><?php echo $row['quantity'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $subtotal;?></td>
</tr>
<?PHP
}
?>
It displays all of the orders from database whereas I want the orders to be displayed for specific company.
If you have button for show only one result you should link it with some id.
For example:
Delete
Make SQL query show only one result: use WHERE clause.
if(isset($_GET['id'])) {
$id = $_GET['id'];
$q = "DELETE FROM table WHERE id = '$id'";
}
$db->query($q);

insert the last 3 visits for each member

i'm designing a Gym Administration System, each member has a unique number stored in a database, each member should type his number when he entered the gym to make sure if his subscription is ended or not, i already design that page, but i need that page to ( add the last 3 visits for each member ) ? how can i do it ?
i need to overwrite the last 3 visits everytime .
ID's 1,2 and 3 are the last visit for member
$con = mysqli_connect('localhost', 'root', '', 'test') or die('error' . mysqli_errno($con));
$query1 = mysqli_query($con, "SELECT * FROM checkin WHERE id = 1");
while ($row = mysqli_fetch_array($query1)){
?>
<div id="checkIn">
<table>
<tr>
<td>Check-In</td>
<td><?php echo $row['timeIn']; ?></td>
<td><?php echo $row['dateIn']; } ?></td>
</tr>
<?php
$query2 = mysqli_query($con, "SELECT * FROM checkin WHERE id = 2");
while ($row = mysqli_fetch_array($query2)){
?>
<tr>
<td>Check-In</td>
<td><?php echo $row['timeIn']; ?></td>
<td><?php echo $row['dateIn']; } ?></td>
</tr>
<?php
$query3 = mysqli_query($con, "SELECT * FROM checkin WHERE id = 3");
while ($row = mysqli_fetch_array($query3)){
?>
<tr>
<td>Check-In</td>
<td><?php echo $row['timeIn']; ?></td>
<td><?php echo $row['dateIn']; } ?></td>
</tr>
</table>
First create a query to fetch all users than loop through them.
$userQuery = $con->prepare("SELECT user_id FROM users");
$userQuery->execute();
$users = mysqli_fetch_array(userQuery);
foreach($users as $user) {
$visitedQuery = $con->prepare("SELECT timeIn, dateIn FROM checkin WHERE user_id = ? ORDER BY id DESC LIMIT 3");
$visitedQuery->execute(array($user['user_id']));
$lastCheckIn = mysqli_fetch_array($visitedQuery);
foreach($lastCheckIn as $lastCheck) {
echo $lastCheckIn['timeIn']." ".$lastCheckIn['dateIn'];
}
}
You mentioned that each user have unique number.
For example:- User A have 123456 unique number.
In Header.php check the condition that user login or not. like:-
if($isset($_SESSION['user_login'])) //you can set your condition here according to your code
{
// first create a new table where user's visit will save.
// Say user database table name is USER_LOGS.which have 3 column.
// ID,User_unique_id,viewpage
$query1 = mysqli_query($con, "SELECT Id,viewpage FROM USER_LOGS WHERE User_unique_id = 12345 ORDER BY Id DESC LIMIT 0"); // that will give you the user's last log.
$total_rows = mysqli_num_rows($query1);
$current_page = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if($total_rows > 0)
{
$row = mysqli_fetch_array($query1);
if($row['viewpage'] != $current_page)
{
mysqli_query($con,"INSERT INTO USER_LOGS (Id,User_unique_id,viewpage)
VALUES ('','123456','".$current_page."')");
}
}
else
{
mysqli_query($con,"INSERT INTO USER_LOGS (Id,User_unique_id,viewpage)
VALUES ('','123456','".$current_page."')");
}
}
The above code is for inert the user log into the database now you can fetch the last three visit by using this query.
mysqli_query($con, "SELECT Id,viewpage FROM USER_LOGS WHERE User_unique_id = 12345 ORDER BY Id DESC LIMIT 0,3");

Categories