Echo after ms sql fetch array does not run - php

I have a SMQL select query which retrieves data from MS Sql server but after the mssql_query, I tried fetching it thru a loop which uses mssql_fetch array but it seems it is skipping the fetch part. Here's my code.
<?php
session_start();
$account = $_REQUEST['name'];
?>
<html>
<head></head>
<body>
<div>
<?php
echo "<table border='1' cellpadding='5' width='100%''>";
echo "<tr><th>No.</th><th>Location</th><th>Engine</th> <th>Time</th></tr>";
// Loop through database
$sql = "SELECT * FROM locations where name = '$account' order by time desc";
//die($sql);
$result = mssql_query($sql);
while ($row = mssql_fetch_array($result)) {
$id = $row['id'];
$location = $row['address'];
$engine = $row['description'];
$time = $row['time'];
// Show entries
echo "<tr>
<td>".$id."</td>
<td>".$location."</td>
<td>".$engine."</td>
<td>".$time."</td>
</tr>";
}
echo "</table>";
?>
</div>
</body>

Related

Output Multiple Database Results

I currently have this code set up:
$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
$data_exist = false;
if (mysqli_num_rows($result) > 0) {
// output data of each row
$data_exist = true;
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$teacher_set = $row["teacher_set"];
$class = $row["class"];
$name = $row["name"];
$description = $row["description"];
}
}
And then:
<?php if ($data_exist){?>
<p><?php echo $id ?></p>
<p><?php echo $teacher_set?></p>
<p><?php echo $name?></p>
<p><?php echo $description?></p>
<?php
}?>
However, the issue is if there is multiple results in the database it only outputs one of them, how can I prevent this from happening and output two?
I want to make it so every row has their own section, like this: http://prntscr.com/hcgtqn so if there is only one result, one one will show etc.
You have to echo data in a loop. Right now you are reassigning values in while($row = mysqli_fetch_assoc($result)) iterations and printing just the last one.
You need to print each time you read a row from the database.
about the styles, you can represent it in many ways. In the code below I present it in a table.
<table>
<thead>
<tr>
<th>id</th>
<th>teacher set</th>
<th>name</th>
<th>description</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
$data_exist = false;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$teacher_set = $row["teacher_set"];
$class = $row["class"];
$name = $row["name"];
$description = $row["description"];
// you need to print the output now otherwise you will miss the row!
// now printing
echo "
<tr>
<td>".$id."</td>
<td>".$teacher_set."</td>
<td>".$name."</td>
<td>".$description."</td>
</tr>";
}
}
else // no records in the database
{
echo "not found!";
}
?>
</tbody>
</table>
</body>
</html>

Can't fetch multiple rows from table

I'm making a page which needs to display all the rows stored in a table named 'events' in a database named 'school'
The problem is that even though I've multiple entries/rows in the table, for some reason only a single row is displayed when I run the page.
Here's my code-
<?php
require("includes/common.php");
$query = "SELECT * FROM school.events";
$result = mysqli_query($con, $query)or die(mysqli_error($con));
$row = mysqli_fetch_array($result);
$ename = $row['name'];
$place = $row['place'];
$date = $row['date'];
?>
.
.
.
<?php
while ($row) {
?>
<tr>
<td><?php echo $date; ?></td>
<td><?php echo $ename; ?></td>
<td><?php echo $place; ?></td>
</tr>
<?php
$row = mysqli_fetch_array($result);
$name = $row['name'];
$place = $row['place'];
$date = $row['date'];
}
?>
Try instead while($row = mysqli_fetch_assoc($result)){ ... } , you're just assigning the array to $row, you can't loop an array saying while($array)
Do it this way:
while($row = mysqli_fetch_assoc($result)){
echo $row['id'];
echo $row['name'];
}
That is because $row = mysqli_fetch_array($result); will only pull one row and then move the pointer. In order to get all the rows, use a while loop
while($row = mysqli_fetch_array($result)) {
//code to populate table one row at a time
}

Sum of while row

I'm new to php and I'm stuck. I have a report that allows a supervisor to show the working hours of the operators. I can show all the hours from the db, but I can't make a sum of all the hours. I want to display one more row that shows the total hours. How can I do that?
<?php
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
include('connect.php');
#$oret_e_punes = $_POST['oret_e_punes'];
#$grupi = $_POST['grupi'];
#$data_e_inserimit = $_POST['data_e_inserimit'];
#$data_e_inserimit_2 = $_POST['data_e_inserimit_2'];
$sql = "select grup_name from grupi";
$result = mysqli_query($dbCon, $sql);
if(!$result) {
die("Error");
}
?>
//html form
<?php
if(isset($_POST['insert'])) {
$insert = "select * from ore where grupi='$grupi' and (data between '$data_e_inserimit' and '$data_e_inserimit_2' and ore !=0)";
$result_insert = mysqli_query($dbCon, $insert);
if(!$result_insert) {
die("Error");
}
echo "<table id='table'>
<tr id='main'>
<td>Operatori</td>
<td>Grupi</td>
<td>Oret e punes</td>
<td>Data</td>
</tr>";
while ($row = mysqli_fetch_assoc($result_insert)) {
$id = $row['id'];
echo "<tr id='sub'>
<td>".$row['usr']."</td>
<td>".$row['grupi']."</td>
<td>".$row['ore']."</td> ---->working hours
<td>".$row['data']."</td>
</tr>";
$id++;
}
echo "</table>";
$_SESSION['$id'] = #$id;
}
?>
have a variable for hours before loop starts. Add in it hour of each record. After loop will end you will have your total hours
echo "<table id='table'>
<tr id='main'>
<td>Operatori</td>
<td>Grupi</td>
<td>Oret e punes</td>
<td>Data</td>
</tr>";
$hours = 0;
while ($row = mysqli_fetch_assoc($result_insert)) {
$id = $row['id'];
echo "<tr id='sub'>
<td>".$row['usr']."</td>
<td>".$row['grupi']."</td>
<td>".$row['ore']."</td> ---->working hours
<td>".$row['data']."</td>
</tr>";
$hours += $row['ore'];
$id++;
}
echo "<tr><td colspan='4'>Total</td><td>$hours</td></tr>";
echo "</table>";

PHP MySQL display data by id from database - freedom placement

I would like to have the freedom to place a row entry from my database wherever i' prefer in the page. Right now, the php code that I use is as follows (it is clean working code):
<html><head></head>
<body>
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
echo $row['id']; while($row = mysql_fetch_array( $result )) {
echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}
?>
</body>
</html>
I call id through the browser Eg. http://site.com/getid.php?id=10 . But I do not have the freedom to place my row entry within my html. For eg. like this:
<table><tr>
<td align="center">BASIC INFO 1: <?php echo $row['basic1']; ?></td>
<td align="center">BASIC INFO 2: <?php echo $row['basic2']; ?></td>
</tr></table>
I can place html within echo PHP tags but then I have to clean up my html and thats a lot of work. Retaining HTML formatting would be preferred. Any help or guidelines on this would be much appreciated.
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
//you need to retrieve every row and save to an array for later access
for($rows = array(); $tmp = mysql_fetch_array($result);)
{
$rows[] = $tmp;
}
//now you can use the $rows array where every you want e.g. with the code from Zhube
?>
....
<table><?php foreach($rows as $r):
<td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>
By
while($row = mysql_fetch_array( $result )) {
echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}
you save only the last row
Instead of having your HTML tags as part of the PHP variable, do something like this instead:
<table><?php foreach($row as $r):?>
<td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>

PHP MySQL undefined Index and other errors

having trouble getting a script of mine to run correctly, I have 2 undefined index errors and an invalid argument supplied error that for the life of me I can't figure out why I'm getting. the 2 undefined index errors come from these lines.
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
and
if (!is_null($_GET['page']))
and my invalid argument error is this
Warning: Invalid argument supplied for foreach() in
generated from this
<?php foreach ($books as $book) : ?>
my full code between the two classes is this.. any ideas of what I've done wrong? tearing my hair out over this.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Catalog</title>
</head>
<body bgcolor="white">
<?php
/////////////////////////////////////////////////
//connect to db
/////////////////////////////////////////////////
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
{
$thesort = $_GET['order'];
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY ".$_GET['order'];
}
else
{
$thesort = "courseTitle";
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY $thesort";
}
//if page is null go to first page otherwise query for correct page
if (!is_null($_GET['page']))
{
$query = $query." LIMIT ".($_GET['page']*8-8).", 8";
}
else
{
$query = $query." LIMIT 0, 8";
}
//query result
$books = $db->query($query);
//get number of overall rows
$query2 = $db->query("SELECT * FROM book");
$count = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$count = $count->fetch();
$count = $count['totalRecords'];
?>
<table border =" 1">
<tr>
<th bgcolor="#6495ed"><a href="?order=course">Course #</th>
<th bgcolor="#6495ed"><a href="?order=courseTitle">Course Title</th>
<th bgcolor="#6495ed"><a href="?order=bookTitle">Book Title</th>
<th bgcolor="#6495ed"></th>
<th bgcolor="#6495ed"><a href="?order=price">Price</th>
</tr>
<?php foreach ($books as $book) : ?>
<tr>
<td><?php echo $book['course']; ?></td>
<td><?php echo $book['courseTitle']; ?></td>
<td><?php echo $book['bookTitle']; ?></td>
<td><?php
$bookcourse = $book['course'];
$isbn = $book['isbn13'];
$booklink = "<a href=\"course.php?course=$bookcourse&isbn=$isbn\">";
echo $booklink ;?><img src='images/<?php echo $book['isbn13'].'.jpg'; ?>'></a></td>
<td><?php echo $book['price']; ?></td>
</tr>
<?php endforeach; ?>
</tr>
</table>
<?php
//paging function... not sure if it works correctly?
for ($j=1; $j <= ceil($count/8); $j++)
{ ?>
<a href=<?php echo "?page=".$j."&order=".$thesort; ?>><?php echo $j; ?></a>
<?php
}?>
</body>
</html>
**course.php**
<?php
//get data from index.php
$course = $_GET['course'];
$isbn = $_GET['isbn'];
//connect to db
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
$query = "Select * FROM book, course, author, publisher
WHERE book.isbn13 = $isbn AND book.course = '$course' AND book.course = course.courseID AND book.bookID = author.bookID AND book.publisher = publisher.publisherID
ORDER BY book.bookID";
//query results
$books = $db->query($query);
//error troubleshooting
if (!$books) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
//count the number of rows in the result
$results = $books->fetchAll();
$rowCount = count($book);
//get data from results
foreach($results as $book){
$bookID = $book['bookID'];
$bookTitle = $book['bookTitle'];
$isbn = $book['isbn13'];
$price = $book['price'];
$desc = $book['description'];
$publisher = $book['publisher'];
$courseTitle = $book['courseTitle'];
$courseID = $book['courseID'];
$credits = $book['credit'];
$edition = $book['edition'];
$publishDate = $book['publishDate'];
$length = $book['length'];
$firstName = $book['firstName'];
$lastName = $book['lastName'];
}
if($numrows > 1)
{
foreach ($books as $book)
{
$authorArray[] = $book['firstName'] + ' ' + $book['lastName'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CIS Department Book Catalog</title>
</head>
<body bgcolor=white">
<table border="0">
<tr>
<td>
<img src='images/<?php echo $isbn.'.jpg'; ?>'>
</td>
<td>
<?php
echo "For Course: $courseID $courseTitle ($credits)";
echo "</br>";
echo "Book Title: $bookTitle";
echo "</br>";
echo "Price: $price";
echo "</br>";
echo "Author";
if ($numResults > 1)
{
echo "s:";
for ($i = 0; $i < $numResults; $i++)
{
if ($i!=0)
echo ", $authorArray[i]";
else
echo $authorArrat[i];
}
}
else
echo ": $firstName, $lastName";
echo "</br>";
echo "Publisher: $publisher";
echo "</br>";
echo "Edition: $edition ($publishDate)";
echo "</br>";
echo "Length: $length pages";
echo "</br>";
echo "ISBN-13: $isbn";
?>
</td>
</tr>
<tr>
<td colspan="2">
<?php echo "Description: $desc"; ?>
</td>
</tr>
</table>
</body>
</html>
You should be using isset not is_null to keep it from warning about undefined variables.
$books is never defined It was defined, just incorrectly ... foreach needs it to be an array. You really don't need it anyway, fetch each row into the array with a while loop. (see my example below). You're also redefining $count several times in your query.
And like #Brad said. Use prepared statements and placeholders. Your database will end up hacked with your current code.
EDIT
Answer to your question. query() returns a statement handle. (I've defined it as $sth). fetch() returns a result which you need to pass one of the fetch mode constants (or define it by default earlier with $db->setFetchMode())
To get the books you need to have
$books = array();
$sth = $db->query($query);
while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
$books[] = $row; // appends each row to the array
}
Here's how your code should look to get a count.
// you're not using the $query2 you defined ... just remove it
$sth = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$result = $sth->fetch(PDO::FETCH_ASSOC);
$count = $result['totalRecords'];
Take a look at:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers Looks like a good guide to give you an in-depth understanding of how to use PDO. Pay special attention to error handling and to prepared statements!

Categories