TWO MySQL commands (SELECT to View), but only one is showing output - php

I have a table and each , I want to select a data from the same table in my database.
For example, first <td> is first name, then the second <td> is phone number.
I got the command, but only the first command is showing output.
This is my php codes to open and connect to the database :
<?php
include("./inc/db_connect.php");
$conn = OpenCon();
?>
This is the php codes for the table including <th> and <td> :
<div class="layer55">
<h3>
<table class="flat-table">
<tbody>
<tr>
<th>
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if ($result = $conn->query($sql)) {
if ($result->num_rows > 0) {
echo "Name";
}
}
?>
</th>
<th>
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if ($result = $conn->query($sql)) {
if ($result->num_rows > 0) {
echo "Phone Number";
}
}
?>
</th>
</tr>
<tr>
<td>
<?php
$sql = "SELECT first_name FROM sharp_emp WHERE employee_id = 'AA170336'";
while ($row = $result->fetch_array()) {
echo "" . $row['first_name'] . "";
}
?>
</td>
<td>
<?php
$sql = "SELECT phone FROM sharp_emp WHERE employee_id = 'AA170336'";
while ($row = $result->fetch_array()) {
echo "" . $row['phone'] . "";
}
?>
</td>
</tr>
</tbody>
</table>
</h3>
</div>
This is the php codes for db_connect.php :
<?php
function OpenCon()
{
$dbhost = "localhost";
$dbuser = // Hidden;
$dbpass = // Hidden;
$db = "sharp_db";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
return $conn;
}
function CloseCon($conn)
{
$conn -> close();
}
?>
The expected output :
|----------|----------|
|Name |Phone Number|
|----------|----------|
|John |179898765 |
The current output :
|----------|----------|
|Name |Phone Number|
|----------|----------|
|John |Null (empty) |

You are running the same query multiple times, overwriting the $result variable for no reason, having useless $sql for the later 2 fetch without using them, and fetching a single $result twice by mistake.
So there are multiple concept problem with your code. I think your current code is something equivalant to this:
<div class="layer55">
<h3>
<table class="flat-table">
<tbody>
<tr>
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if ($result = $conn->query($sql)) {
if ($result->num_rows > 0) {
?>
<th>Name</th>
<th>Phone Number</th>
<?php } else { ?>
<th></th>
<th></th>
<?php } ?>
<?php } ?>
</tr>
<tr>
<?php if ($row = $result->fetch_array()) { ?>
<td><?php echo "" . $row['first_name'] . ""; ?></td>
<td><?php echo "" . $row['phone'] . ""; ?></td>
<?php } else { ?>
<td></td>
<td></td>
<?php } ?>
</tr>
</tbody>
</table>
</h3>
</div>
But frankly, it makes no sense to me to print an empty table when there is no result. So what you need is probably something like this.
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if (
($result = $conn->query($sql))
&& ($result->num_rows > 0)
&& ($row = $result->fetch_array())
):
?>
<div class="layer55">
<h3>
<table class="flat-table">
<tbody>
<tr>
<th>Name</th>
<th>Phone Number</th>
</tr>
<tr>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['phone']; ?></td>
</tr>
</tbody>
</table>
</h3>
</div>
<?php endif; ?>

Related

PHP Mysql query optimization for report

I have this report which filters data from 5 tables but it is very slow takes around 10 seconds. I tried using index on some columns but it did not help.
Basically the first query is the master and the others are for filtering it if the other queries condition met then it will skip it.
this is the script:
<div class="col-md-12">
<h3>List of Outstandings</h3>
<table class="table table-condensed table-bordered table-hover small">
<thead>
<tr>
<th >#</th>
<th>PR #</th>
<th>PR Type</th>
<th>Description</th>
<th>Dep.</th>
<th>Date</th>
<th>Requester</th>
<th>Assigned to</th>
</tr>
</thead>
<tbody>
<?php
$chkk = 0;
$sql = "SELECT * FROM msr WHERE Status ='Approved' ";
$result6 = $connn->query($sql);
if ($result6->num_rows > 0) {
$vo = 1;
while ($row0 = $result6->fetch_assoc()) {
$chkk = 0;
$MSRID = $row0["MSRID"];
$MSRType = $row0["MSRType"];
$result4 = "SELECT owner FROM tracking WHERE MSRID='$MSRID' ";
$MyRow4 = $connn->query($result4);
$row4 = $MyRow4->fetch_assoc();
$actionBy = $row4["owner"];
$resultusr = "SELECT RFQID FROM rfq WHERE MSRID='$MSRID' AND NOPO='No' ";
$MyRowusr = $connn->query($resultusr);
$rowusr = $MyRowusr->fetch_assoc();
$rfqcount = mysqli_num_rows($MyRowusr);
if ($rfqcount > 0) {
$chkk = 1;
}
$resultusr4 = "SELECT POID FROM po WHERE MSRID='$MSRID' ";
$MyRowusr4 = $connn->query($resultusr4);
$rowusr4 = $MyRowusr4->fetch_assoc();
$rfqcount4 = mysqli_num_rows($MyRowusr4);
if ($rfqcount4 > 0) {
$chkk = 1;
}
$resultusr1 = "SELECT MSRID FROM contract WHERE MSRID='$MSRID' ";
$MyRowusr1 = $connn->query($resultusr1);
$rowusr1 = $MyRowusr1->fetch_assoc();
$rfqcount1 = mysqli_num_rows($MyRowusr1);
if ($rfqcount1 > 0) {
$chkk = 1;
}
if ($chkk == 1) {
continue;
}
?>
<tr>
<td>
<?php echo $vo; ?>
</td>
<td>
<?php echo $row0["MSRID"]; ?>
</td>
<td>
<?php echo $row0["MSRType"]; ?>
</td>
<td>
<?php echo $row0["purposeofbuying"]; ?>
</td>
<td>
<?php echo depName($row0["DepRequester"]); ?>
</td>
<td>
<?php echo $row0["RequestDate"]; ?>
</td>
<td>
<?php echo reqName($row0["RequestPer"]); ?>
</td>
<td>
<?php echo reqName($actionBy); ?>
</td>
</tr>
<?php
$vo++;
}
}
?>
</tbody>
</table>
</div>
</div>
You can use subquery method instead of looping.
Example:
$sql = "SELECT *,
( SELECT owner
FROM tracking
WHERE tracking.MSRID= msr.MSRID
) AS _owner,
( SELECT RFQID
FROM rfq
WHERE rfq.MSRID= msr.MSRID
AND rfq.NOPO='No'
) AS _RFQID
FROM msr
WHERE rfq.Status ='Approved'";

Displaying data in tables depending on group

I have a question in relation to displaying PHP tables that should be straight forward but I cannot get my head around it at the moment so any help would be appreciated, basically what I want to do is display a team of players in a table, but display multiple tables of users with their team name display above it.
What I currently have : http://puu.sh/ilUJp/4a6ae5e47b.png
What I am looking to achieve : http://puu.sh/ilUJ8/7756033517.png
<div class="col-lg-6">
<h3>Team Name Goes Here </h3>
<?php
echo "<table class='table table-striped'>";
echo " <thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
";
while($row = mysqli_fetch_array($result)) {
$teamName = $row['teamName'];
$fName = $row['firstName'];
$surName = $row['surName'];
echo "
<tbody>
<tr>
<td>$teamName</td>
<td>$fName</td>
<td>$surName</td>
</tr>
</tbody>
";
}
echo "</table>";
?>
</div>
with my query :
$sql = "SELECT t.teamID,t.teamName,u.firstName,u.surName From users as u INNER JOIN team as t where u.teamID = t.teamID ";
I know the idea I need to do but cannot get it done, so any help would be appreciated.
Try this code
<?php $teemid=array();
while($row = mysqli_fetch_array($result)) {
if(!in_array($row['teamID'],$teemid)){
array_push($teemid,$row['teamID']);
if(!empty($teemid)){ ?>
</tbody>
</table>
</div>
<?php }
?>
<div class="col-lg-6">
<h3><?php echo $row['teamName']; ?></h3>
<table class='table table-striped'>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php } ?>
<tr>
<td><?php echo $row['teamName']; ?></td>
<td><?php echo $row['firstName']; ?></td>
<td><?php echo $row['surName']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
SQL Query Change as below
$sql = "SELECT t.teamID,t.teamName,u.firstName,u.surName From users as u INNER JOIN team as t where u.teamID = t.teamID ORDER BY u.teamID";
You can do this logic
$teams = "get all teams sql query";
while ($row = mysqli_fetch_array($teams)) {
$teamid = $row['teamid'];
$teamname = $row['teamname'];
$teammemberquery = "select all member in the where team = $teamid sql query";
echo "<table>";
while ($r = mysqli_fetch_array($teammemberquery)) {
$teamName = $r['teamName'];
$fName = $r['firstName'];
$surName = $r['surName'];
echo "
<tbody>
<tr>
<td>$teamName</td>
<td>$fName</td>
<td>$surName</td>
</tr>
</tbody>
";
}
echo "</table>";
}
Try as below (Please replace table column name as yours and mysql to mysqli):
<?php
$link = mysql_connect('localhost', 'root', 'root');
$db_selected = mysql_select_db('test', $link);
$sql = "SELECT t.team_id,t.team,u.fname,u.lname,u.email From users as u INNER JOIN team as t where u.team_id = t.team_id order by t.team_id ";
$result = mysql_query($sql);
?>
<html><head><title>team</title></head><body><div class="col-lg-6">
<?php
echo "<table>";
$teamName = "";
$i=0;
while($row = mysql_fetch_array($result))
{
if($teamName == "" || $teamName != $row['team'])
{
if($i!=0)
echo "</table>";
echo "<tr><td colspan='3'><h3>".$row['team']."</h3></td></tr>";
$teamName = $row['team'];
$i=0;
}
$fName = $row['fname'];
$surName = $row['lname'];
$email = $row['email'];
if($i==0)
{
echo "<table class='table table-striped'><tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>";
}
echo "<tr>
<td>$fName</td>
<td>$surName</td>
<td>$email</td>
</tr>";
$i++;
}
echo "</table>";
?>
</div></body></html>

retrieve and add the data into database

I need to retrieve the relevant data from database, and add to the attendance table again. this code shows many error. actually i dunno how to use the array to add the data. can anyone help?? thankssssssssssss.
<?php
$sql = "select p_module_ID, student_ID,
p_attendance_Date, p_attendance_Time,
p_attendance_Status,p_attendance_reason
from attendance";
$result = mysqli_query($con, $sql);
if(!$result)
{
echo mysqli_error($con);
exit();
}
while($rows = mysqli_fetch_array($result))
{
$attendance_list[] = array('p_module_ID' => $rows['p_module_ID'],
'student_ID' => $rows['student_ID'],
'p_attendance_Date' => $rows['p_attendance_Date'],
'p_attendance_Time' => $rows['p_attendance_Time'],
'p_attendance_Status' => $rows['p_attendance_Status'],
'p_attendance_reason' => $rows['p_attendance_reason']);
}
?>
<html>
<body>
<form action="attendance.php" method="post" accept-charset='UTF-8'>
<table border="0" cellspacing="20" >
<tr>
<td>
<select name="p_module_ID">
<?php
$sql = "SELECT p_module_ID FROM schedule";
$result = $con->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<option>".$row['p_module_ID']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>
<select name="p_attendance_Date" >
<?php
$sql = "SELECT p_StartDate FROM schedule";
$result = $con->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<option>".$row['p_StartDate']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>
<select name="p_attendance_Time">
<?php
$sql = "SELECT p_Time FROM schedule";
$result = $con->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<option>".$row['p_Time']."</option>";
}
?>
</select>
</td>
</tr>
<table id="t01">
<tr>
<th> Student ID </th>
<th> Name </th>
<th> Attendance </th>
<th> Reason </th>
<?php foreach($attendance_list as $attend) : ?>
<tr>
<td>
<?php
$sql = "SELECT p.student_ID,CONCAT(s.student_fname, ' ', s.student_lname) AS fullname FROM Pals p JOIN student s ON p.student_ID = s.student_ID WHERE student_role = 'Student' GROUP BY student_ID";
$result = $con->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo $attend[$row['student_id']];
}
?>
</td>
<td>
<?php
$sql = "SELECT p.student_ID,CONCAT(s.student_fname, ' ', s.student_lname) AS Fullname FROM Pals p JOIN student s ON p.student_ID = s.student_ID WHERE student_role = 'Student' GROUP BY student_ID";
$result = $con->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo $attend['Fullname'];
}
?>
</td>
<td>
<?php echo $attend["p_attendance_Status"]; ?>
</td>
<td>
<?php echo $attend["p_attendance_reason"]; ?>
</td>
</tr>
</tr>
<?php endforeach; ?>
</table>
</table>
</form>
</body>
</html>
Use $row['student_Id'] instead of $row['student_id']. Same as for Fullname. You selecting AS fullname not AS Fullname. Listen to the case sensitiveness.

how to give style to the SQL table when checkbox selected?

SO i have form which consist of "Event Name" "Event Description" "Event Date" and checkbox "is important". When i check checkbox value "yes" its important, it sends to the sql value = "1" to table "is_important". Everything is all right, but i give the bootstrap style "bg-danger" for that "is_important" = 1 table and it doesnt show up. What's the problem?
You can see in the code:
<?php
if (isset($_POST['important'])) {
$error = array();
$success = array();
$eventTime = time();
$important = $_POST['important'];
$eventName = trim(mysql_real_escape_string($_POST['EventName']));
$eventDesc = htmlentities(trim(mysql_real_escape_string($_POST['EventDesc'])), ENT_QUOTES);
if (!isset($eventName) || empty($eventName)) {
$error['eventName'] = "Prasome ivesti ivykio varda";
} else if (strlen($eventName) > 32 || strlen($eventName) < 3) {
$error['eventName'] = "Ivykio pavadinimas turi buti tarp 3 ir 32 simboliu";
}
if (!isset($eventDesc) || empty($eventDesc)) {
$error['eventDesc'] = "Prasome ivesti ivykio aprasyma";
}
if (empty($error)) {
$sql = "INSERT INTO notes_list (title, description, timestamp,is_important) VALUES ('$eventName', '$eventDesc','$eventTime','$important')";
$result = mysqli_query($con, $sql);
$success[] = "SEKME !";
} else {
}
}
?>
<table class="table table-striped">
<thead>
<tr>
<th>Event name</th>
<th>Event description</th>
<th>Event date</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM notes_list ORDER BY id DESC LIMIT 10";
$result2 = mysqli_query($con, $query);
print_r($_POST);
if ($result2) {
while ($note = mysqli_fetch_assoc($result2)) {
?>
<tr<?php echo (($note['is_important'] == 1) ? "class='bg-danger'" : ""); ?>>
<td><?php echo $note['title']; ?></td>
<td><?php echo $note['description'] ?></td>
<td><?php echo date('l M jS', $note['timestamp']); ?></td>
</tr>
<?php
}
mysqli_free_result($result2);
}
/* close connection */
mysqli_close($con);
?>
</tbody>
</table>
Full Example in this picture:
https://www.dropbox.com/s/h650h2spy2487dm/chechbox.jpg?dl=0
This:
<tr<?php echo (($note['is_important'] == 1) ? "class='bg-danger'" : ""); ?>>
would render this:
<trclass='bg-danger'>
in case is_important is 1. You need a space there, before the class.

Call to undefined function ProdTotal()

I am trying to call function ProdTotal to get the total quantity order and total amount ordered for a product and load it in the table in the Display Function. I am getting the error: Call to undefined function ProdTotal();
<?php
Class CarsClass {
private $user = 'php06';
private $pwd = 'php06';
private $dbConn;
function __construct($db='classicmodels') {
//Create connection to MySQL database requested, if blank just connect up.
$this->dbConn = new mysqli('localhost', $this->user, $this->pwd, $db);
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select count(*) as 'custcount' from customers";
$result = $this->dbConn->query($query);
$row = $result->fetch_assoc();
$custCount = $row['custcount'];
print "Connected to DB $db as user $this->user<br><br> Number of Rows $custCount<br><br>";
}
function __destruct(){
mysqli_close();
Print "DB closed by user <br><br>";
}
function header(){
echo "Midterm Exam Script 2 Header<br><br>";
}
function display(){
$totqty = 0;
$totamt = 0;
//get row from WB_Resident Table
$query = "select productCode,productName,productDescription,quantityInStock,buyprice,MSRP from products";
$result = $this->dbConn->query($query);
?>
<table id="midterm2">
<tr>
<th colspan="13">Product Database Table</th>
</tr>
<tr>
<th width="2%">productCode</th>
<th width="10%">productName</th>
<th width="10%">productDescription</th>
<th width="10%">quantity in stock</th>
<th width="10%">buyPrice</th>
<th width="2%">MSRP</th>
<th width="10%">Total Qty Ordered</th>
<th width="10%">Total $ Ordered</th>
</tr>
<?php
while($row = $result->fetch_assoc()):
$producta = $row["productCode"];
ProdTotal($producta);
?>
<tr>
<td>
<?php echo $row["productCode"]; ?>
</td>
<td>
<?php echo $row["productName"];?>
</td>
<td>
<?php echo $row["productDescription"]; ?>
</td>
<td>
<?php echo $row["Qty In Stock"]; ?>
</td>
<td>
<?php echo $row["Buy Price"]; ?>
</td>
<td>
<?php echo $row["MSRP"]; ?>
</td>
<td>
<?php echo $totqty; ?>
</td>
<td>
<?php echo $totamt; ?>
</td>
</tr>
<?php
endwhile;
?>
</table>
<?php
}
function footer(){
echo "Midterm Exam Script 3 Footer<br><br>";
}
function ProdTotal($product){
echo "product code entered = $product <br><br>";
$query = "select RTRIM(productCode) as productt, quantityOrdered, priceEach from orderdetails order by productt";
$result = $this->dbConn->query($query);
while($row = $result->fetch_assoc()){
if ($row["productt"] == $product){
echo $row;
$total = $row["quantityOrdered"] * $row["priceEach"];
$totqty = $totqty + $row["quantityOrdered"];
$totamt = $totamt + $total;
echo totqty;
echo totamt;
return array($totqty, $totamt);
}
}
}
}
?>
This script is executed to call class.
<html>
<head>
<title>Midterm2 Script 3</title>
<link rel="stylesheet" type="text/css" href="midterm2.css" />
</head>
<body>
<?php
require 'CarsClass3a.php';
$obj1= new CarsClass('classicmodels');
$obj1->header();
$obj1->display();
$obj1->footer();
?>
</body>
</html>
In display(), change the call to ProdTotal() to
list($totqty, $totamt) = $this->ProdTotal($producta);

Categories