PHP: No output from $row variable even if it is already defined - php

I don't know why it doesn't show up anything, I already tested my query and it is working in my phpmyadmin, but in my php code it does not work upon adding the AS keyword. My goal for this is to place a value to a variable coming from the SUM() keyword.
<?php
require_once "user-connect.php";
$user = $_SESSION['id'];
$sql = "SELECT SUM(total) AS sumz FROM cart WHERE userID = $user AND month(orderDate) = month(now()) AND day(orderDate) = day(now())";
$result = $link->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo $row['sumz'];
}
if (mysqli_query($link, $sql)) {
} else {
echo "Error: " . $sql . "" . mysqli_error($link);
} ?>
<table cellspacing="0">
<tbody>
<tr class="cart-subtotal">
<th>Cart Subtotal</th>
<td><span class="amount"><?php echo $row['sumz']; ?></span></td>
</tr>

You can use:
$sql = "SELECT SUM(total) FROM cart WHERE..."
And in HTML:
<td><span class="amount"><?php echo $row['SUM(total)']; ?></span></td>

Take a look at PHP fetch assoc guide.
while ($row = $result->fetch_assoc()) {
echo $row['sumz'];
}
An example of getting the SUM value
<?php
$sql="SELECT sum(amount) as total FROM table";
$result = mysqli_query($sql);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['total'];
}
mysqli_close($con);
?>

Related

How do I display different table from 1 table? Like each table has unique code

This are my db table:
But my query only get 1 row for each table like this:
As you can see, there are 2 tables for 1003 because it has 2 rows. It should be only one (1) table of 1003 with 2 rows. How do I fix this? EXPECTED RESULT:
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone GROUP BY model";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row["model"]?></td>
</tr>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You have at least 5 problems here,
[edit: problem 1 removed & changed sample based on extended answer]
Inside your while { ... } loop, you're printing an entire table, when you should only be printing the <tr>...</tr> part there. This is what causes additional table(s).
And 3rd problem: your "no_record" line is a loose <td>. Not only isn't it inside the table (which is covered in problem #2), it's also not wrapped with a <tr>.
4th problem: You're randomly printing the echo $row["brand_code"] outside of the table.
5th problem: you're printing raw data from the database as if it is valid html, it more than likely is not. it has to be probably encoded with htmlentities/htmlspecialchars.
Quick & dirty fixed version:
function tableOpen($row) {
printf( '<h1>%s</h1>', htmlentities($row["brand_code"]) );
echo '<table id="table_stock" class="">';
echo '<thead>';
echo '<tr>';
echo '<th>Model</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
}
function tableClose() {
echo '</tbody>';
echo '</table><br>';
}
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone ORDER BY brand_code";
$lastBrand = null;
if ($result = mysqli_query($db, $query)) {
if (mysqli_num_rows($result) > 0) {
if ($lastBrand !== $row["brand_code"] && !is_null($lastBrand)) tableClose();
if ($lastBrand !== $row["brand_code"]) tableOpen($row);
$lastBrand = $row["brand_code"];
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
printf( '<td>%s</td>', htmlentities($row["model"]) );
echo '</tr>';
}
tableClose();
/// Free result
mysqli_free_result($result);
} else {
echo '<p class="no_record">No records found.</p>';
}
} else {
echo "ERROR: Not able to execute \$query: <br>" . htmlentities($query) . '<br>' . htmlentities(mysqli_error($link));
}
you need additional loop. Also in the first query you need to use group by codes.
$query = "SELECT model, brand_code FROM smartphone GROUP BY brand_code";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<?php
if ($result1 = mysqli_query($db, "SELECT DISTINCT model, brand_code FROM smartphone WHERE brand_code={$row["brand_code"]}"))
{
while ($row1 = mysqli_fetch_array($result1))
{
// get count for each model within brand_code
$cnt = ($result2 = mysqli_query($db, "SELECT COUNT(*) AS cnt FROM smartphone WHERE brand_code={$row["brand_code"]} AND model='{$row1["model"]}'")) && ($row2 = mysqli_fetch_array($result2)) ? $row2["cnt"] : "---";
?>
<tr>
<td><?php echo $row1["model"] ({$cnt})?></td>
</tr>
<?php
}
mysqli_free_result($result1);
}
?>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

MySQL - Select row values from url ID

I created a table which is updated through a form and each row gets assigned a specific number.
When viewing this table, I want to click on that assigned number and get a page where all the details of that row are displayed.
If I do $sql = "SELECT * FROM clients WHERE nif_id='114522';"; - where the nif_id is the assigned number - I get the values for that number, but I need it to change with every number in the table.
Any ideas?
UPDATE
This is the table code:
<div class="card card-body">
<table class="table">
<thead>
<tr>
<th>NIF</th>
<th>Nome</th>
<th>Apelido</th>
<th>Telemóvel</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<?php
include_once '../includes/db.inc.php';
$sql = "SELECT * FROM clients ORDER BY nif_id ASC;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$first = $row["prm_nome"];
$last = $row["apelido"];
$phone = $row['nmr_tlm'];
$email = $row['mail'];
$nif = $row['nif_id'];
echo '<tr>';
echo '<td>'.$nif.'</td>';
echo '<td>'.$first.'</td>';
echo '<td>'.$last.'</td>';
echo '<td>'.$phone.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
</div>
You can use the get request parameters.
ex: www.myapp.com/table?id=3920393
add functionality in your PHP file as follows
if(isset($_GET["id"])){
$id = $_GET["id"];
$sql = "SELECT * FROM clients WHERE nif_id='".$id."';";
//make db call & display HTML
}
This is a very simple implementation and does not implement any security or SQL injection security. This was more of a conceptual answer as to how you can tackle your problem.
This is quite a common scenario for web-based systems.
<div class="card card-body">
<table class="table">
<thead>
<tr>
<th>NIF</th>
<th>Nome</th>
<th>Apelido</th>
<th>Telemóvel</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<?php
include_once '../includes/db.inc.php';
$sql = "SELECT * FROM clients ORDER BY nif_id ASC;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$first = $row["prm_nome"];
$last = $row["apelido"];
$phone = $row['nmr_tlm'];
$email = $row['mail'];
$nif = $row['nif_id'];
echo '<tr>';
echo '<td>'.$nif.'</td>';
echo '<td>'.$first.'</td>';
echo '<td>'.$last.'</td>';
echo '<td>'.$phone.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
</div>
where the detail.php is another page to query specific details regarding the query nifid.
As a reminder, if the data type of the column is INT, there is no need to use single quotes to surround the value in the SQL statement.
Sample detail.php:
<?php
if(!isset($_GET['nifid']) || (int)$_GET['nifid'] <= 0) {
// Invalid or missing NIFID
header('Location: table.php');
}
include_once '../includes/db.inc.php';
$id = (int)$_GET['nifid'];
$sql = "SELECT * FROM clients WHERE nif_id=$id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
// TODO: display the result in whatever way you like
?>

Update link for each table row

With the code i have i can succesfully read and display data from my database,
"agencies_validation" does this. I also manage to make it so it display Update Link for each row. But the Update link doesen't work. So what i want it to do is when i click Update link it calls "agencies_admin_update.php" which is supposed to Update that row. But it doesn't work.
//agencies_validation
<table border="2">
<tr>
<td>title</td>
</tr>
<?php
include_once 'database.php';
echo '<form action= "agencies_admin_update.php" method="get">';
$valid_query = "SELECT * FROM agencies ";
$valid_result = mysqli_query($link, $valid_query);
while ($row = mysqli_fetch_array($valid_result)) {
echo '<tr>';
$id = $row['id'];
echo '<td>'.$row['title'].'</td>';
echo "<td><a href='agencies_admin_update.php?'>UPDATE</a></td>";
echo '<tr>';
}
echo '</form>';
?>
</table>
and
//agencies_admin_update.php
<?php
include_once 'database.php';
$id = $_GET['id'];
$query = "UPDATE agencies SET admin=2 WHERE id = $id";
header("Location: agencies_validation.php");
?>
The first you have to add the ID to link URL:
...
echo "<td><a href='agencies_admin_update.php?id=" . $id . "'>UPDATE</a></td>";
...
The second you must not only to generate the SQL query, but and execute it:
...
$query = "UPDATE agencies SET admin=2 WHERE id = $id";
mysqli_query($link, $query)
...
If this is really all code, then I think, you are just specifying your query in agencies_admin_update.php and not executing it.
See here:
$query = "UPDATE agencies SET admin=2 WHERE id = $id";
The $query variable is set, but not executed.
After specifying the variable you are redirecting the user immidiately with this code:
header("Location: agencies_validation.php");
But I'm wondering, how this should work, because you have no $id specified, which you want to update in agencies_admin_update.php.
Try this!!!
<td><a href='agencies_admin_update.php?id=<?php echo $row['id']; ?>'>UPDATE</a></td>
You need to execute the update query in the agencies_admin_update.php file and send id with the url in agencies_validation file
//agencies_validation
<table border="2">
<tr>
<td>title</td>
</tr>
<?php
include_once 'database.php';
echo '<form action= "agencies_admin_update.php" method="get">';
$valid_query = "SELECT * FROM agencies ";
$valid_result = mysqli_query($link, $valid_query);
while ($row = mysqli_fetch_array($valid_result)) {
echo '<tr>';
$id = $row['id'];
echo '<td>'.$row['title'].'</td>';
echo "<td><a href='agencies_admin_update.php?id=".$id."'>UPDATE</a></td>";
echo '<tr>';
}
echo '</form>';
?>
</table>
Execute query in this file
// agencies_validation
<?php
include_once 'database.php';
$id = $_GET['id'];
$query = "UPDATE agencies SET admin=2 WHERE id = $id";
$result = mysqli_query($link, $query);
if($result) {
// Show success message
header("Location: agencies_validation.php");
} else {
// Show error message
header("Location: agencies_validation.php");
}
?>

How to connect php to navicat with 2 tables

$i = 1;
$sql = "
SELECT
heroes.char_id, characters.char_name, heroes.class_id, heroes.count,
heroes.played, heroes.active FROM heroes, characters
WHERE characters.obj_Id = heroes.char_id AND heroes.played = 1
";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query))
{
echo "
<tr>
<td><span id='lefttop'><b><font color='#007aa2'>".$i++." </font></td><td><b><font color='#f6ff00'>".$row['char_name']."</font></td></span><div style='float:right;'><td><b> ".$row['count']."</td></div> <br />
</tr>
";
}
echo "";
?>
Anyone can help? im trying to make a hero status script on a java server, and i need to connect into 2 tables which is "heroes"(this is where i get the hero) and "character" (this is where i get the hero names)
Try this Temple:
<?php
$sql1 = "SELECT * your table1";
$query1 = mysql_query($sql);
while($row1 = mysql_fetch_array($query1))
{
echo "<tr>";
$sql2 = "SELECT * your table2";
$query2 = mysql_query($sql2);
while($row2 = mysql_fetch_array($query2))
{
echo "<td>[yor Vars here]</td>";
}
echo "</tr>";
}
?>

PHP Output of SQL Query

As of now I have no errors in my program, but I need the primary key for one of the tables for a relation for the following Query. but instead of getting a actual number the value the query is sending back is Resource id #4
Here is my Code: (The query that I'm having issues with is the $sql_branch, is there a function to change the result from "Resource id #4" to just 4?
$sql_branch = "SELECT BranchNum
FROM Branch
WHERE BranchName = '$_POST[branch]'";
$sql_result = "SELECT AuthorFirst, AuthorLast, OnHand, Title
FROM Inventory i, Wrote w, Author a, Book b
WHERE i.BookCode = b.BookCode AND i.BookCode = w.BookCode
AND a.AuthorNum = w.AuthorNum AND i.BranchNum = 1";
$connect = mysql_connect('students', 'xxxx', 'xxxx') or exit(mysql_error());
mysql_select_db('henrybooks', $connect);
if(mysql_query($sql_branch, $connect)) {
$branch = mysql_query($sql_branch, $connect);
}
else {
echo mysql_error();
}
if(mysql_query($sql_result, $connect)) {
$result = mysql_query($sql_result, $connect);
}
else {
echo mysql_error();
}
echo $branch."<br>";
echo $sql_branch."<br>";
echo "<table>
<tr>
<td>Author</td>
<td>Title</td>
<td>Number Available</td>
</tr>";
while( $row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row['AuthorFirst'].$row['AuthorLast']."</td>";
echo "<td>".$row['Title']."</td>";
echo "<td>".$row['OnHand']."</td>";
echo "</tr>";
}
echo "</table>";
?>
Thanks!
You are not pulling results from the mysql_query. Try this:
if($branch_result = mysql_query($sql_branch, $connect)) {
$branch = mysql_fetch_array($branch_result);
}

Categories