I've searched high and low for this and I can't wrap my head around it. I have a form to search Permit Applications. Input your permit number and it runs 3 queries against 3 separate SQL Server views. The queries are almost identical in the same if statement but the last one fails. I've performed a var_dump($query_insp_history) copied the output and run a new query directly in SSMS and it works just fine. Is there some other error checking that will give me more detail other than sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given? I believe I have my parameters setup correctly, please let me know if it should be structured differently.
The // Application Inspection History Section is the part giving me issues. I just can't figure it out as it appears it's setup the same way the other two queries are. I receive the error at this line of code while($row = sqlsrv_fetch_array($sql_insp_history, SQLSRV_FETCH_ASSOC)){
var_dump($sql_insp_history); returns bool(false)
var_dump($query_insp_history); returnsstring(81) "SELECT * FROM my.dbo.vw_Permit_App_Insp_History WHERE (LTRIM(APNO) = '123456')"Again, copying this into SSMS runs correctly...
Thank you in advance.
Here is my code.
<div class="container content">
<form method="POST" name="permit_search" action="">
<input type="number" id="apno" name="apno" class="col-sm-8">
<input type="submit" name="apnosearch" id="apnosearch" value="Submit" class="col-sm-4">
</form>
<br/>
<?php
error_reporting(E_ALL ^ E_NOTICE);
$serverName = "my_server";
$connectionInfo = array( "Database"=>"myDb", "UID"=>"myUser", "PWD"=>"myPass", "ReturnDatesAsStrings" => true);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if($conn === false) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
// Query variables
$searchapno = $_POST['apno'];
$where_permit_info = "WHERE (LTRIM(APNO) = '$searchapno')";
$where_review_history = "WHERE (LTRIM(APNO) = '$searchapno') ORDER BY ACTTYPE, TYPENO ASC";
$where_insp_history = "WHERE (LTRIM(APNO) = '$searchapno') ORDER BY INSPTYPE, TYPENO ASC";
$query_permit_info = "SELECT TOP 1 * FROM my.dbo.vw_Permit_Information $where_permit_info";
$query_review_history = "SELECT * FROM my.dbo.vw_Permit_Plan_Review_History $where_review_history";
$query_insp_history = "SELECT * FROM my.dbo.vw_Permit_App_Insp_History $where_insp_history";
// Overall Permit Information
if (isset($_POST['apno'])) {
$sql_permit_info = sqlsrv_query($conn, $query_permit_info);
while ($row= sqlsrv_fetch_array($sql_permit_info, SQLSRV_FETCH_ASSOC)) {
echo "<strong>Name:</strong> ".$row['APNAME']."<br>";
echo "<strong>Number:</strong> ".$row['APNO']."<br>";
echo "<strong>Address:</strong> ".$row['STNO']." ".$row['PREDIR']." ".$row['STNAME']." ".$row['SUFFIX']." ".$row['POSTDIR']."<br>";
echo "<strong>Description:</strong> ".$row['DESCRIPT']."<br>";
echo "<strong>Status:</strong> ".$row['STAT']."<br>";
echo "<h3>Application Stages</h3><br>";
echo "<strong>Date Processed:</strong> ".$row['ADDDTTM']."<br>";
echo "<strong>Date Issued:</strong> ".$row['ISSDTTM']."<br>";
}
sqlsrv_free_stmt( $sql_permit_info);
// Plan Review History Section
echo "<h3>Plan Review History</h3>";
echo "<div class='nimbus_table_minimal'>";
echo "<table cellspacing='0' cellpadding='0'>
<thead>
<tr>
<th>Description</th>
<th>Added</th>
<th>Status</th>
<th>Status Date</th>
<th>Dept</th>
</tr>";
$sql_review_history = sqlsrv_query($conn, $query_review_history);
while($row = sqlsrv_fetch_array($sql_review_history, SQLSRV_FETCH_ASSOC)){
echo "<tbody>";
echo "<tr>";
echo "<td>".$row['DESCRIPT']." ".$row['TYPENO']."</td>";
echo "<td>".$row['ADDDTTM']."</td>";
echo "<td>".$row['STAT']."</td>";
echo "<td>".$row['STATDTTM']."</td>";
echo "<td>".$row['DEPT']."</td>";
echo "</tr>";
}
sqlsrv_free_stmt( $sql_review_history);
echo "</tbody></table></div>";
// Application Inspection History Section
echo "<h3>Application Inspection History</h3>";
echo "<div class='nimbus_table_minimal'>";
echo "<table cellspacing='0' cellpadding='0'>
<thead>
<tr>
<th>Number and Inspection</th>
<th>Status</th>
<th>Inspector</th>
</tr>";
$sql_insp_history = sqlsrv_query($conn, $query_insp_history);
while($row = sqlsrv_fetch_array($sql_insp_history, SQLSRV_FETCH_ASSOC)){
echo "<tbody>";
echo "<tr>";
echo "<td>".$row['DESCRIPT']." ".$row['TYPENO']."</td>";
echo "<td>".$row['STAT']."</td>";
echo "<td>".$row['EMPLAST']."</td>";
echo "</tr>";
}
sqlsrv_free_stmt( $sql_insp_history);
echo "</tbody></table></div>";
}
?>
</div>
According to its documentation, sqlsrv_query() returns false if it gets an error or a statement resource on success.
You must get in the habit of checking errors in SQL operations, or you'll never know whose woods you stop near, Mr. Frost.
You want something like this:
$sql_permit_info = sqlsrv_query($conn, $query_permit_info);
if ($sql_permit_info === false) {
die( print_r( sqlsrv_errors(), true));
}
while ($row= sqlsrv_fetch_array($sql_permit_info, SQLSRV_FETCH_ASSOC)) {
Something must be incorrect with the View I was using. I pulled the raw SELECT statement out of the view and inserted into my $sql_permint_info and all is working fine now.
Related
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);
}
I am trying to update a specific row in a table; however, when the query runs, it updates the last record added instead of the record selected.
The SQL statement was taken straight from phpmyAdmin. I have tried "UPDATE registration_tbl SET Paid = 'PAID' WHERE ID='$row21'" and that still did not work.
Have I put something wrong in the code?
<table class="table table-striped table-hover table table-responsive-sm table-responsive-md table-responsive-lg">
<tr>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th>Sex</th>
<th>Age</th>
<th>Address Type</th>
<th>Address 1</th>
<th>Address 2</th>
<th>Home</th>
<th>Work</th>
<th>Cell</th>
<th>Email Address</th>
<th>Congregation</th>
<th>RMC</th>
<th>Auxillary</th>
<th>Occupation</th>
<th>Category</th>
<th>Username</th>
<th>Submission Date</th>
<th>Payment Status</th>
<th>Action</th>
</tr>
<?php
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result_set = mysqli_query($conn,"SELECT * FROM registration_tbl");
$num_messages = mysqli_num_rows($result_set);
$num = 0;
while($row = mysqli_fetch_array($result_set))
{
$row1 = $row["Title"];
$row2 = $row["FirstName"];
$row3 = $row["LastName"];
$row4 = $row["Sex"];
$row5 = $row["Age"];
$row6 = $row["AddressType"];
$row7 = $row["Address1"];
$row8 = $row["Address2"];
$row9 = $row["Home"];
$row10 = $row["Work"];
$row11 = $row["Cell"];
$row12 = $row["EmailAdd"];
$row13 = $row["Congregation"];
$row14 = $row["RMC"];
$row15 = $row["Auxillary"];
$row16 = $row["Occupation"];
$row17 = $row["Category"];
$row18 = $row["Username"];
$row19 = $row["DateSubmitted"];
$row20 = $row["Paid"];
$row21 = $row["ID"];
$num++;
echo "<tr>";
echo "<td>$row1</td>";
echo "<td>$row2</td>";
echo "<td>$row3</td>";
echo "<td>$row4</td>";
echo "<td>$row5</td>";
echo "<td>$row6</td>";
echo "<td>$row7</td>";
echo "<td>$row8</td>";
echo "<td>$row9</td>";
echo "<td>$row10</td>";
echo "<td>$row11</td>";
echo "<td>$row12</td>";
echo "<td>$row13</td>";
echo "<td>$row14</td>";
echo "<td>$row15</td>";
echo "<td>$row16</td>";
echo "<td>$row17</td>";
echo "<td>$row18</td>";
echo "<td>$row19</td>";
echo "<td>$row20</td>";
if($row20 != "PAID")
{
echo "<td><input type='submit' class='btn btn-success' name='paid' value='PAID' /></td></tr>";
}
}
echo "</table></br>";
echo "<table><tr><td>";
echo $num_messages . " Registration(s) Found!";
echo "</td></tr></table>";
if(isset($_POST['paid']))
{
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$updatePaymentStmt = "UPDATE `registration_tbl` SET `Paid` = 'PAID' WHERE `registration_tbl`.`ID` = $row21;";
if(mysqli_query($conn, $updatePaymentStmt))
{
echo "<script>alert('Payment updated successfully!')</script>";
}
else
{
echo "<script>alert('Error in updating Payment!')</script>";
}
}
I think you're going to want a separate form for each row in the table. And you'll need a hidden field in that form containing the ID so the server knows which ID to process when it receives the submission.
Remove any <form>...</form> tags you may have placed to wrap around the whole table, and instead use:
if($row20 != "PAID")
{
echo "<td><form action='' method='post'><input type='submit' class='btn btn-success' name='paid' value='PAID' /><input type='hidden' name='id' value='".$row["ID"]."'/></form></td></tr>";
}
and then
if(isset($_POST['paid']))
{
$id = $_POST["id"];
///etc, you can now use $id in a parameter in your query, to select the correct row
P.S. The rest of the code could also be greatly simplified, as others have mentioned in the comments, and you should definitely fix the SQL injection issue - that's a serious security problem.
This bug comes about from a flaw in your thinking rather than unexpected behaviour in the code.
Effectively you have a while loop that iterates over the entire results set (from the first query) and updates the $row* variables. What this means is that $row21 is always going to be the last selected record. If you were to chuck an ORDER BY id DESC on the end you'd find that the first record was always updated...
So what you actually want to do is add the id into the button - and make each button it's own form - so that when the form is posted the intended id is in the button's value.
Something like:
<?php
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$registrations = $mysqli->query($conn,"SELECT * FROM registration_tbl");
$num_messages = $registration->num_rows;
while ($row = $registrations->fetch_assoc() {
echo "<tr>";
echo "<td>{$row["Title"]}</td>";
echo "<td>{$row["FirstName"]}</td>";
echo "<td>{$row["LastName"]}</td>";
echo "<td>{$row["Sex"]}</td>";
echo "<td>{$row["Age"]}</td>";
echo "<td>{$row["AddressType"]}</td>";
echo "<td>{$row["Address1"]}</td>";
echo "<td>{$row["Address2"]}</td>";
echo "<td>{$row["Home"]}</td>";
echo "<td>{$row["Work"]}</td>";
echo "<td>{$row["Cell"]}</td>";
echo "<td>{$row["EmailAdd"]}</td>";
echo "<td>{$row["Congregation"]}</td>";
echo "<td>{$row["RMC"]}</td>";
echo "<td>{$row["Auxillary"]}</td>";
echo "<td>{$row["Occupation"]}</td>";
echo "<td>{$row["Category"]}</td>";
echo "<td>{$row["Username"]}</td>";
echo "<td>{$row["DateSubmitted"]}</td>";
echo "<td>{$row["Paid"]}</td>";
echo $row["Paid"]] !== "PAID" ?
"<td><form method='post'><button class='btn btn-success' name='paid' value='{$row["ID"]}'>Paid</button></form></td>" :
"<td></td>";
}
echo "</tr>";
}
echo "</table></br>";
echo "<table><tr><td>";
echo $num_messages . " Registration(s) Found!";
echo "</td></tr></table>";
if ($_POST['paid'] ?? null) {
$sql = "UPDATE `registration_tbl` SET `Paid` = 'PAID' WHERE `registration_tbl`.`ID` = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("i", $_POST["paid"]);
echo $query->execute() ?
"<script>alert('Payment updated successfully!')</script>" :
"<script>alert('Error in updating Payment!')</script>";
}
}
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
This code is giving me and unexpected end of file. any help?
im trying to make a sinmple page that has many different queries on it. im making one page as it just keeps things in one place and to save time. anyone got any recommendations?
<?php
$host="127.0.0.1";
$username="root";
$pword="";
$database="spm";
require("db_connection.php");
//for searching by customer name
$customername1 = $_POST['customername1'];
//variables for inserting new restaurant
$restname = $_POST['restname'];
$restaddress = $_POST['restaddress'];
$resthomephone = $_POST['resthomephone'];
$restcolpoints = $_POST['restcolpoints'];
$restdelpoints = $_POST['restdelpoints'];
?>
<html>
<head>
<title>Database search</title>
</head>
<body>
<?php
$custidtosearch = "";
$query_string = "SELECT custID FROM customertable WHERE custname ='".$customername1."'";
if ($result = $mysqli -> query($query_string)) {
while ($row = $result -> fetch_object()) {
$custidtosearch = $row->dateid;
//echo $custidtosearch;
}
Echo "</table>";
$result->close();
}else{
echo ("there was an error or there was no query");
}
$query_string = "SELECT * FROM orderlist WHERE custid = '".$custidtosearch."'" ;
//echo $query_string;
if ($result = $mysqli -> query($query_string)) {
echo "<table border = '1'>";
echo "<tr><th> Customer Name</th> <th>Order ID</th> <th>Customer ID</th> <th>Restaurant ID</th> <th>Order points</th> <th>Customer Points used</th></tr>";
while ($row = $result -> fetch_object()) {
Echo "<tr>".$row->$customername1."</td>";
Echo "<td>".$row->PersonID."</td>";
Echo "<td>".$row->Name."</td>";
Echo "<td>".$row->mobile."</td>";
Echo "<td>".$row->email."</td>";
Echo "<td>".$row->dateid."</td></tr>";
}
Echo "</table>";
$result->close();
$query_string = "INSERT INTO `restauranttable`(`restname`, `address`, `phoneno`, `colpoints`, `delpoints`) VALUES ('".$restname."','".$restaddress."','".$resthomephone."',
'".$restcolpoints."','".$restdelpoints."')";
if ($result = $mysqli -> query($query_string)) {
Echo ("Restaurant added");
$result->close();
}else{
echo ("there was an error or there was no query");
}
$mysqli->close();
?>
<p><a href=enterpageuni.php />Back</a></p>
</body>
</html>
You're missing a closing } for one of your code blocks. Probably from the first if ($result = $mysqli -> query($query_string)) { (before you open the <table>. The end of file is "unexpected" because PHP is still waiting for that code block to be closed.
Your IF-STATEMENT is missing a closing tag. You need to check your code to verify where the closing tag should be placed.
if ($result = $mysqli -> query($query_string)) {
echo "<table border = '1'>";
echo "<tr><th> Customer Name</th> <th>Order ID</th> <th>Customer ID</th> <th>Restaurant ID</th> <th>Order points</th> <th>Customer Points used</th></tr>";
while ($row = $result -> fetch_object()) {
Echo "<tr>".$row->$customername1."</td>";
Echo "<td>".$row->PersonID."</td>";
Echo "<td>".$row->Name."</td>";
Echo "<td>".$row->mobile."</td>";
Echo "<td>".$row->email."</td>";
Echo "<td>".$row->dateid."</td></tr>";
}
Echo "</table>";
$result->close();
} //<!--- I'm guessing this where the close tag should go.
I am trying to filter a mysql table using PHP, My aim is when the url is History.php?h_id=1 it only shows the rows that have one in the h_id (H_id is not a unique number)
My code is as below.
<html>
<head>
<title></title>
</head>
<body >
<?php
mysql_connect('localhost', 'root', 'matl0ck') or die(mysql_error());
mysql_select_db("kedb") or die(mysql_error());
$h_id = (int)$_GET['h_id'];
$query = mysql_query("SELECT * FROM Hist WHERE H_ID = '$h_id'") or die(mysql_error());
if(mysql_num_rows($query)=1){
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
?>
<?php
$con=mysqli_connect("localhost","root","matl0ck","kedb");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Hist");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
<th>H_ID</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['DateMod'] . "</td>";
echo "<td>" . $row['H_ID'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</body>
</html>
When I try to use this it shows all records that has a number in the h_id when I delete a number in this column it shows an error.
My table layout is as below.
Thank you
This is your syntactically incorrect statement
if(mysql_num_rows($query)=1){
A test is done using == and = is a value assignment
if(mysql_num_rows($query) == 1){
//------------------------^^
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
Also
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements and therefore stick to the mysqli_ or PDO database extensions
Your general code seemed to get a bit confused, and you were getting data from a query "SELECT * FROM Hist" that you never seemed to use.
Also the while loop was being terminated before you actually consumed and output the results of the first query.
I also amended the code to use parameterized and prepared queries, and removed the use of the mysql_ which no longer exists in PHP7
<?php
// Use one connection for all script, and make it MYSQLI or PDO
$con=mysqli_connect("localhost","root","matl0ck","kedb");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
// if connection fails there is no point doing anything else
exit;
}
//$h_id = (int)$_GET['h_id'];
// prepare and bind values to make the code safe from SQL Injection
// also only select the rows you want
$sql = "SELECT ID, Name, DateMod, H_ID FROM Hist WHERE H_ID = ?";
$stmt = $con->prepare($sql);
if ( ! $stmt ) {
echo $con->error;
exit;
}
$stmt->bind_param("i", $_GET['h_id']);
$stmt->execute();
if ( ! $stmt ) {
echo $con->error;
exit;
}
// bind the query results 4 columns to local variable
$stmt->bind_result($ID, $Name, $DateMod, $H_ID);
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
if($con->affected_rows > 0){
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
while($stmt->fetch()) {
while($row = $stmt->fetch_array()) {
echo "<tr>";
echo "<td>$ID</td>";
echo "<td>$Name</td>";
echo "<td>$DateMod</td>";
echo "<td>$H_ID</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo 'No entry found. Go back';
}
?>
I created a database in xampp, made a very simple php script that access/connect to mysql in xampp(saved it to xampp/htdocs). The connection is ok, but when I ran it to a browser, only a table I created in php appeared but the data in mysql did not. What could be the problem?
Here is the php code:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM example")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['age'];
echo "</td></tr>";
}
echo "</table>";
?>
If you just started to use PHP and MySQL why not starting to learn PDO as mysql_* functions are deprecated.
Make sure you have data in the example table, check with PHPMyAdmin and follow this nice guide.
Your code should be:
<?php
$db = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
$stmt = $db->query("SELECT * FROM example");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['age'];
echo "</td></tr>";
}
echo "</table>";
?>