PHP Database Table Display - php

I have an assignment in which needs to be corrected. My code has all working functionality. However, I need my code to be able to display my reservations table when the page is initially opened and loaded. Currently, the table is only shown when another flight is added. I believe I am missing a few lines of code or am not putting the code in the correct section. Please help.
> <html>
<head>
<title>HW09</title>
</head>
<body>
<h1>HW09 - Airline Reservation</h1>
<form>
<h3>Find a flight:</h3>
<?php
include("config.php");
$connect=mysqli_connect("localhost",$username,$dbpassword,"CHA") or die ("Cannot open database");
$sql="SELECT * FROM `AirportList` ";
$result = mysqli_query($connect,$sql);
print "<label>From: </label>";
print "<select name='from'>";
while ($row = $result -> fetch_assoc()) {
print "<option value='" . $row['AirportCode'] . "'>" . $row['AirportName'] . "</option>\n";
}
print "</select>\n";
print "<br>";
$result = mysqli_query($connect,$sql);
print "<label>To: </label>";
print "<select name='to'>";
while ($row = $result -> fetch_assoc()) {
print "<option value='" . $row['AirportCode'] . "'>" . $row['AirportName'] . "</option>\n";
}
print "</select>\n";
print "<br>";
print "<label>Date: </label>";
print "<input type=\"date\" name=\"datee\" id=\"datee\" >";
print"<br>
<input type='submit' value='Find Flights'>
</br>";
$de = $_GET['datee'];
$d = str_replace("-","",$de);
$from = $_GET['from'];
$to = $_GET['to'];
$sql2 = "SELECT * FROM `Flights` WHERE `Date` LIKE '$d' AND `Takeoff` LIKE '$from' AND `Landing` LIKE '$to' ";
print "<br />";
if ($_GET) {
print "<p>Let's find a reservation</p>";
$result2 = mysqli_query($connect,$sql2);
$count = 0;
while ($num = $result2 -> fetch_assoc()) {
$count = $count + 1;
}
print "<p>We have " . $count . " options</p><br />";
$result2 = mysqli_query($connect,$sql2);
if ($_GET['datee']) {
print "
<table border=1>
<tr>
<th>Select</th>
<th>Seats</th>
<th>From</th>
<th>To</th>
<th>Time</th>
<th>Flight#</th>
</tr>";
}
while ($info = $result2 -> fetch_assoc()) {
print"
<form>
<tr>
<td>
<input type='hidden' name='addflight' value=" . $info['Serial'] . ">
<input type='submit' name='Reserve' value='Reserve'>
</td>
<td>
<select name='seats'>";
for ($x = 1; $x <= 11; $x++) {
print"<option value= " . $x . ">" . $x . "</option>";
}
print"</td>
<td>" . $info['Takeoff'] . "</td><td>" . $info['Landing'] . "<td>" . $info['Time'] . "</td><td>" . $info['Flightnum'] . "</td></tr>
</form>";
}
print "</table>";
if (isset($_GET['Reserve'])) {
$connect3=mysqli_connect("localhost",$username,$dbpassword,"jasonlalaki_HW09") or die ("Cannot open database");
$sql3="INSERT INTO `Reservations` (`ResSerial`, `Seats`) VALUES (" . $_GET['addflight'] . ", " . $_GET['seats'] . ");";
$result3 = mysqli_query($connect3,$sql3);
$sql4="SELECT * FROM `Reservations` ";
$result4 = mysqli_query($connect3,$sql4);
print"
<table border=1>
<tr>
<th>Delete</th>
<th>Date</th>
<th>Time</th>
<th>Flight</th>
<th>From</th>
<th>To</th>
<th>Seats</th>
</tr>";
while ($row1 = $result4 -> fetch_assoc()) {
$sql5="SELECT * FROM `Flights` WHERE `Serial` = " . $row1['ResSerial'];
$result5 = mysqli_query($connect,$sql5);
while ($info2 = $result5 -> fetch_assoc()) {
print"
<form>
<tr>
<td>
<input type='submit' name='Delete' value='Delete'>
</td>
<td>" . $info2['Date'] . "</td><td>" . $info2['Time'] . "</td><td>" . $info2['Flightnum'] . "</td><td>" . $info2['Takeoff'] . "</td><td>" . $info2['Landing'] . "</td><td style=\"text-align: right;\">" . $row1['Seats'] . "</td></tr>
</form>";
}
}
print"
</table>";
}
}
?>
</form>
</body></html>

After studying your code a bit, I decided to rewrite it - including the naming conventions of the tables, to show you a "best practice" example. The table structures chosen by me are certainly not the correct ones, but I didn't consider this here of big relevance.
Suggestions:
You should always avoid printing HTML code using PHP code. For example, avoid snippets like this: print "<label>From: </label>";. Write HTML code as normal: <label>From: </label>.
There are the cases where PHP code must be printed inside HTML controls (values, attributes, etc). Then try to print only PHP variables, no complex code. Instead of <input value="<?php echo $selectedFlightDate ?? ''; ?>" ... /> optimize to <?php $defaultFlightDate = $selectedFlightDate ?? ''; ?> <input value="<?php echo $defaultFlightDate; ?>" ... />.
Try to separate the database querying PHP codes from the rest of the page. The querying results should be fetched in arrays, which will easily be used later in the page.
Don't hesitate to use pronounceable and intention-revealing names for variables, constants, functions, etc. So, instead of <input type="date" name="datee"> use <input type="date" name="flightDate">. Or, in PHP, instead of $de = $_GET['datee']; use $flightDate = $_GET['flightDate'];.
You are using MySQLi extension. I suggest you to use the object oriented classes and methods of it, instead of the procedural functions of it. For example, instead of $connection = mysqli_connect(/* args list */); (procedural style) you should use $connection = new mysqli(/* args list */); (object oriented style). See the docs.
You are using MySQLi database extension, but I strongly advice you to switch to the PDO extension as soon as possible!
In order to avoid malicious SQL injections, you should always use the so-called prepared statements. You'll notice that I never used mysqli_query, because it's not compatible with the process of statements preparing. I commented my code a lot, especially where I prepared the SQL statement for fetching the flights list (SELECT * FROM flights WHERE ...).
Code:
Change my db credentials with yours.
I appended the string "_test" to all table names for quickly creating them without affecting yours, and testing.
connection.php:
<?php
/*
* This page contains the code for creating a mysqli connection instance.
*/
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'tests');
define('PASSWORD', 'tests');
// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER !!! */
/*
* Enable internal report functions. This enables the exception handling.
*
* #link http://php.net/manual/en/class.mysqli-driver.php
* #link http://php.net/manual/en/mysqli-driver.report-mode.php
* #link http://php.net/manual/en/mysqli.constants.php
*/
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create a new db connection.
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);
index.php:
<?php
require 'connection.php';
/*
* ==================================================================
* Define flags for the various operations. Can be very useful later.
* ==================================================================
*/
$searchingFlightsStarted = false;
$flightReservationStarted = false;
$reservationDeletionStarted = false;
/*
* =========================================================
* Operations upon submission of form "searchingFlightsForm"
* =========================================================
*/
if (isset($_POST['searchFlightsButton'])) {
$searchingFlightsStarted = true;
/*
* Read submitted values.
*/
$selectedStartingAirport = $_POST['startingAirport'] ?? '';
$selectedDestinationAirport = $_POST['destinationAirport'] ?? '';
// I didn't applied any formatting to the date value. Do it, if you need to.
$selectedFlightDate = $_POST['flightDate'] ?? '';
/*
* Validate submitted values.
*/
if (empty($selectedStartingAirport)) {
$errorMessages[] = 'Please select a starting point.';
}
if (empty($selectedDestinationAirport)) {
$errorMessages[] = 'Please select a destination.';
}
if (empty($selectedFlightDate)) {
$errorMessages[] = 'Please select a date for the flight.';
}
/*
* If no validation errors yet, proceed with searching flights.
* Note the use of the prepared statement in order to avoid malicious SQL injections.
*/
if (!isset($errorMessages)) {
/*
* The SQL statement to be prepared. Notice the so-called markers,
* e.g. the "?" signs. They will be replaced later with the
* corresponding values when using mysqli_stmt::bind_param.
*
* #link http://php.net/manual/en/mysqli.prepare.php
*/
$sql = 'SELECT *
FROM flights_test
WHERE
date = ? AND
takeoff LIKE ? AND
landing LIKE ?';
/**
* Prepare the SQL statement for execution, but
* ONLY ONCE - read the docs to find out why.
*
* #link http://php.net/manual/en/mysqli.prepare.php
*/
$statement = $connection->prepare($sql);
$boundSelectedStartingAirport = '%' . $selectedStartingAirport . '%';
$boundSelectedDestinationAirport = '%' . $selectedDestinationAirport . '%';
/*
* Bind variables for the parameter markers ("?") in the
* SQL statement that was passed to prepare(). The first
* argument of bind_param() is a string that contains one
* or more characters which specify the types of the
* corresponding bind variables (string, integer, etc).
*
* #link http://php.net/manual/en/mysqli-stmt.bind-param.php
*/
$statement->bind_param(
'sss',
$selectedFlightDate,
$boundSelectedStartingAirport,
$boundSelectedDestinationAirport
);
/*
* Execute the prepared SQL statement.
* When executed any parameter markers which exist,
* e.g. each "?" character, will automatically be
* replaced with the appropriate data.
*
* #link http://php.net/manual/en/mysqli-stmt.execute.php
*/
$statement->execute();
/*
* Get the result set from the prepared statement.
*
* NOTA BENE:
* Available only with mysqlnd ("MySQL Native Driver")! If this
* is not installed, uncomment "extension=php_mysqli_mysqlnd.dll" in
* php.ini and restart web server and mysql service. Or use the following instead:
* mysqli_stmt::store_result + mysqli_stmt::bind_result + mysqli_stmt::fetch.
*
* #link http://php.net/manual/en/mysqli-stmt.get-result.php
* #link https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
*/
$result = $statement->get_result();
// Fetch all found flights and save them in an array for later use.
$foundFlights = $result->fetch_all(MYSQLI_ASSOC);
/*
* Free the memory associated with the result. You should
* always free your result when it is not needed anymore.
*
* #link http://php.net/manual/en/mysqli-result.free.php
*/
$result->close();
/*
* Close the prepared statement. It also deallocates the statement handle.
* If the statement has pending or unread results, it cancels them
* so that the next query can be executed.
*
* #link http://php.net/manual/en/mysqli-stmt.close.php
*/
$statement->close();
}
}
/*
* ==========================================================
* Operations upon submission of form "flightReservationForm"
* ==========================================================
*/
if (isset($_POST['reserveFlightButton'])) {
$flightReservationStarted = true;
/*
* Read submitted values.
*/
$flightIdToReserve = $_POST['flightIdToReserve'];
$seatToReserve = $_POST['seatToReserve'];
/*
* Proceed with the reservation of the selected flight.
* Note the use of the prepared statement.
*/
$sql = 'INSERT INTO reservations_test (
flight_id,
seat
) VALUES (
?, ?
)';
$statement = $connection->prepare($sql);
$statement->bind_param('ii', $flightIdToReserve, $seatToReserve);
$statement->execute();
$statement->close();
$successMessages[] = 'The reservation of the selected flight was successfully performed.';
}
/*
* ============================================================
* Operations upon submission of form "reservationDeletionForm"
* ============================================================
*/
if (isset($_POST['deleteReservationButton'])) {
$reservationDeletionStarted = true;
/*
* Read submitted values.
*/
$reservationIdToDelete = $_POST['reservationIdToDelete'];
/*
* Proceed with the deletion of the selected flight.
* Note the use of the prepared statement.
*/
$sql = 'DELETE FROM reservations_test
WHERE id = ?';
$statement = $connection->prepare($sql);
$statement->bind_param('i', $reservationIdToDelete);
$statement->execute();
$statement->close();
$successMessages[] = 'The selected flight reservation was successfully deleted.';
}
/*
* ===========================================================
* Fetch the airports list (used in the searching comboboxes).
* Note the use of the prepared statement.
* ===========================================================
*/
$sql = 'SELECT * FROM airports_test';
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->get_result();
// Fetch all airports and save them in an array for later use.
$airports = $result->fetch_all(MYSQLI_ASSOC);
$result->close();
$statement->close();
/*
* =======================================================
* Fetch the reservations list, which is always displayed.
* Note the use of the prepared statement.
* =======================================================
*/
$sql = 'SELECT
r.id,
r.flight_id,
f.date,
f.time,
f.flight_no,
f.takeoff,
f.landing,
r.seat
FROM reservations_test AS r
LEFT JOIN flights_test AS f ON
r.flight_id = f.id';
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->get_result();
// Fetch all reservations and save them in an array for later use.
$reservations = $result->fetch_all(MYSQLI_ASSOC);
$result->close();
$statement->close();
?>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<title>Demo</title>
<link href="styles.css" rel="stylesheet">
</head>
<body>
<header>
<h1>
Airline Reservation
</h1>
</header>
<section class="messages">
<?php
/*
* Display all error messages.
*/
if (isset($errorMessages)) {
foreach ($errorMessages as $errorMessage) {
?>
<div class="error">
<?php echo $errorMessage; ?>
</div>
<?php
}
}
/*
* Display all success messages.
*/
if (isset($successMessages)) {
foreach ($successMessages as $successMessage) {
?>
<div class="success">
<?php echo $successMessage; ?>
</div>
<?php
}
}
?>
</section>
<section>
<header>
<h3>
Search flights:
</h3>
</header>
<article>
<form id="searchingFlightsForm" method="post" action="">
<div class="form-group">
<label>From: </label>
<select name="startingAirport">
<option value="">-- Select a starting point --</option>
<?php
if ($airports) {// if any records available
foreach ($airports as $airport) {
$airportCode = $airport['code'];
$airportName = $airport['name'];
$attributeSelected = ($airportCode === $selectedStartingAirport) ?
'selected' :
'';
?>
<option value="<?php echo $airportCode; ?>" <?php echo $attributeSelected; ?>>
<?php echo $airportName; ?>
</option>
<?php
}
}
?>
</select>
</div>
<div class="form-group">
<label>To: </label>
<select name="destinationAirport">
<option value="">-- Select a destination --</option>
<?php
if ($airports) {// if any records available
foreach ($airports as $airport) {
$airportCode = $airport['code'];
$airportName = $airport['name'];
$attributeSelected = ($airportCode === $selectedDestinationAirport) ?
'selected' :
'';
?>
<option value="<?php echo $airportCode; ?>" <?php echo $attributeSelected; ?>>
<?php echo $airportName; ?>
</option>
<?php
}
}
?>
</select>
</div>
<div class="form-group">
<label>Date: </label>
<?php $defaultFlightDate = $selectedFlightDate ?? ''; ?>
<input type="date" id="flightDate" name="flightDate" value="<?php echo $defaultFlightDate; ?>" />
</div>
<div class="form-group">
<label> </label>
<button type="submit" name="searchFlightsButton" class="formButton" value="Search Flights">
Search Flights
</button>
</div>
</form>
</article>
</section>
<?php
$numberOfFoundFlights = isset($foundFlights) ? count($foundFlights) : 0;
?>
<section>
<header>
<h3>
<?php
$foundFlightsMessage = $numberOfFoundFlights > 0 ?
'Found flights: ' . $numberOfFoundFlights . '. Let\'s make a reservation.' :
'No flights found yet.';
echo $foundFlightsMessage;
?>
</h3>
</header>
<?php
if ($numberOfFoundFlights > 0) {
?>
<article>
<table>
<thead>
<tr>
<th>Select</th>
<th>Seat</th>
<th>From</th>
<th>To</th>
<th>Time</th>
<th>Flight #</th>
</tr>
</thead>
<tbody>
<?php
foreach ($foundFlights as $foundFlight) {
$flightId = $foundFlight['id'];
$flightTakeoff = $foundFlight['takeoff'];
$flightLanding = $foundFlight['landing'];
$flightTime = $foundFlight['time'];
$flightNumber = $foundFlight['flight_no'];
?>
<tr>
<td>
<?php
/*
* You are not allowed to enclose a table row in a "form" tag!
* Though, in HTML5, you can define a form for each table row
* wherever you want on the page, and then add the attribute "form"
* to each control residing outside of it, but destined to belong
* to it. The "form" attribute MUST contain the id of the form
* to which the current control should belong. As example see
* the comboboxes named "seatToReserve" bellow.
*/
?>
<form id="flightReservationForm_<?php echo $flightId; ?>" class="flightReservationForm" method="post" action="">
<input type="hidden" name="flightIdToReserve" value="<?php echo $flightId; ?>">
<button type="submit" name="reserveFlightButton" class="columnButton" value="Reserve">
Reserve
</button>
</form>
</td>
<td>
<select name="seatToReserve" form="flightReservationForm_<?php echo $flightId; ?>">
<?php
for ($seat = 1; $seat <= 11; $seat++) {
?>
<option value="<?php echo $seat; ?>">
<?php echo $seat; ?>
</option>
<?php
}
?>
</select>
</td>
<td><?php echo $flightTakeoff; ?></td>
<td><?php echo $flightLanding; ?></td>
<td><?php echo $flightTime; ?></td>
<td><?php echo $flightNumber; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</article>
<?php
}
?>
</section>
<?php
$numberOfReservations = $reservations ? count($reservations) : 0;
?>
<section>
<header>
<h3>
<?php
$reservationsMessage = $numberOfReservations > 0 ?
'Reservations:' :
'No reservations available yet.';
echo $reservationsMessage;
?>
</h3>
</header>
<?php
if ($numberOfReservations > 0) {
?>
<article>
<table>
<thead>
<tr>
<th>Delete</th>
<th>Date</th>
<th>Time</th>
<th>Flight</th>
<th>From</th>
<th>To</th>
<th>Seat</th>
</tr>
</thead>
<tbody>
<?php
foreach ($reservations as $reservation) {
$reservationId = $reservation['id'];
$reservationFlightId = $reservation['flight_id'];
$reservationDate = $reservation['date'];
$reservationTime = $reservation['time'];
$reservationFlightNumber = $reservation['flight_no'];
$reservationTakeoff = $reservation['takeoff'];
$reservationLanding = $reservation['landing'];
$reservationSeat = $reservation['seat'];
?>
<tr>
<td>
<form id="reservationDeletionForm_<?php echo $reservationId; ?>" class="reservationDeletionForm" method="post" action="">
<input type="hidden" name="reservationIdToDelete" value="<?php echo $reservationId; ?>">
<button type="submit" name="deleteReservationButton" class="columnButton" value="Delete">
Delete
</button>
</form>
</td>
<td><?php echo $reservationDate; ?></td>
<td><?php echo $reservationTime; ?></td>
<td><?php echo $reservationFlightNumber; ?></td>
<td><?php echo $reservationTakeoff; ?></td>
<td><?php echo $reservationLanding; ?></td>
<td><?php echo $reservationSeat; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</article>
<?php
}
?>
</section>
</body>
</html>
styles.css:
*, *::before, *::after { box-sizing: border-box; }
:root { font-size: 16px; }
body { margin: 0; padding: 20px; font-family: "Verdana", Arial, sans-serif; font-size: 1rem; font-weight: 400; background-color: #fff; }
table { border-collapse: collapse; }
table, th, td { border: 1px solid #ccc; }
th, td { padding: 7px; text-align: left; }
th { background-color: #f4f4f4; }
tbody tr:hover { background: yellow; }
.messages { width: 50%; }
.messages .error { background-color: #e83e8c; color: #fff; padding: 5px; margin: 5px; }
.messages .success { background-color: #5cb85c; color: #fff; padding: 5px; margin: 5px; }
#searchingFlightsForm { width: 50%; padding: 20px; background-color: #f4f4f4; }
#searchingFlightsForm .form-group { padding: 5px; }
#searchingFlightsForm label { display: inline-block; min-width: 70px; }
#searchingFlightsForm select { min-width: 240px; }
#searchingFlightsForm input[type="date"] { min-width: 240px; padding: 7px; }
.formButton { padding: 5px 7px; background-color: #009926; color: #fff; }
.columnButton { padding: 3px 5px; background-color: #0086b3; color: #fff; }
form.flightReservationForm { margin: 0; }
form.reservationDeletionForm { margin: 0; }
The used table definitions and testing data:
"airports_test" table:
CREATE TABLE `airports_test` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(100) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
id|code|name |
--|----|--------------------|
1|LON |London Airport |
2|BUA |Buenos Aires Flights|
3|BUD |Budapest Airport |
"flights_test" table:
CREATE TABLE `flights_test` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`date` varchar(10) DEFAULT NULL,
`time` time DEFAULT NULL,
`takeoff` varchar(100) DEFAULT NULL,
`landing` varchar(100) DEFAULT NULL,
`flight_no` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
id|date |time |takeoff|landing|flight_no|
--|----------|--------|-------|-------|---------|
1|2020-12-27|15:38:00|BUA |BUD |43245 |
2|2020-12-29|22:44:00|BUD |LON |245 |
3|2020-12-30|05:31:00|BUD |BUA |876643 |
4|2020-12-30|10:00:00|LON |BUD |5443 |
5|2020-12-30|18:45:00|LON |BUD |4287 |
"reservations_test" table:
CREATE TABLE `reservations_test` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`flight_id` bigint(20) unsigned DEFAULT NULL,
`seat` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8
id|flight_id|seat|
--|---------|----|
Resources:
(The only proper) PDO tutorial
How to use mysqli properly
PHP error reporting
Clean, high quality code: a guide on how to become a better programmer

I took one of your sql statements and made it a prepaired statement.
You need preparied statements id Mike O'Leary need to fly to O'Heir airport.
<?php
$msi = new mysqli('localhost','misc01','!howTO001','test');
$stmt = $msi->prepare('
Select
*
From
Flights
Where
Date LIKE ? And
Takeoff LIKE ? And
Landing LIKE ?
';
$stmt->bind_param('sss', $d, $from, $to);
$stmt->execute();
$rslt = $stmt->get_result();
echo('<pre>');
print_r($rslt->fetch_all(MYSQLI_ASSOC));

Related

count the rows in a table and change the width of a single column ..?

i need to get the counting of the table rows in order as a column in column "N"
also i need to make the column"N" width looks smaller than others columns
i think i have done everything but this is the only point i couldn't achieved
the output should be as the picture :
i hope you could help me guys, thank you
here is my codes :
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
// DataBase connection
$host = "localhost";
$user = "root";
$password = "";
$db = "worksheet9";
$con = mysqli_connect($host, $user, $password, $db);
//verfiy Connection
if( mysqli_connect_errno()) {
echo " Connection Error:" . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
$task=$_POST['task'];
// insert sql query
$sql = "INSERT INTO dolist (task) VALUES ('$task')";
$result=mysqli_query($con, $sql);
// verify query
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
<form method='POST'>
<input type="text" name="task" id="task" required
placeholder="add task" oninvalid="this.setCustomValidity('you must fill the task')"
oninput="this.setCustomValidity('')">
<input type="submit"name="submit"value="add task" ><!-- comment -->
</form>
<table border="1">
<tr>
<th> N </th>
<th>ID </th>
<th>task</th>
<th>delete</th><!-- comment -->
<th>update</th>
</tr>
<?php
// Select sql query
$sql = "SELECT ID,task FROM dolist";
$result = mysqli_query($con, $sql);
while ($rows = mysqli_fetch_array($result)) {
echo"<form method ='POST'>";
echo "<tr>";
echo "<td>" . "<input type='number' readonly name='number' value='" . $rows[''] . "'></td>";
echo "<td>" . "<input type='text' readonly name='id' value='" . $rows['ID'] . "'></td>";
echo "<td>" . "<input type='text' name='task' value= '" . $rows['task'] . "'></td>";
echo "<td>" . "<input type='submit' name='delete' value='x'>" . "</td>";
echo "<td>" . "<input type='submit' name='update' value='update'>" . "</td>";
echo "</tr>";
echo "</form>";
}
if(isset($_POST['update'])) {
$sql = "UPDATE dolist SET task='$_POST[task]'WHERE ID=$_POST[id]";
$result = mysqli_query($con,$sql) or die(mysqli_connect_errno());
if($result){
echo "updated";
} else {
echo "update faild";
}
}
//perform only when the user click on Delete
if(isset($_POST['delete'])) {
$sql = "DELETE FROM dolist WHERE ID=$_POST[id]";
$result = mysqli_query($con,$sql) or die(mysqli_connect_errno());
if($result){
echo "DELETED";
}else{
echo "delete faild";
}
}
?>
</table>
</body>
</html>
For row numbering add a counter to your PHP code:
$rowNumber = 1;
while ($rows = mysqli_fetch_array($result)){
echo"<form method ='POST'>";
echo "<tr>";
echo "<td>" . $rowNumber++. "</td>";
// echo other fields...
echo"</tr>";
For formatting, give your table an ID (not essential but it makes the CSS styling more specific)
This should then generate HTML like this:
<table id="results">
<tr><th>N</th><th>ID</th><th>task</th><th>Delete</th><th>Update</th></tr>
<tr><td>1</td><td>11</td><td>task</td><td>X</td><td>Update</td></tr>
<tr><td>2</td><td>12</td><td>task</td><td>X</td><td>Update</td></tr>
</table>
Now you can style it with CSS:
/* Border around the table */
#results {
border: 1px solid grey;
}
/* Border around the individual cells */
#results th, #results td {
border: 1px solid gray;
}
/* Set the width of the first TH. Also sets the width of the res of the column */
#results th:first-of-type {
width:1em;
}
/* Set the width of the 3rd column (the 'task' column */
#results th:nth-of-type(3) {
width:10em;
}
Output:
Note: you could do this by adding class attributes to the <th> elements and styling those. It makes for easier maintenance later.
Use of formatting attributes in HTML tags (like BORDER="1") is considered bad practice and should be avoided.
Don't use JS or PHP to count something pure CSS can help you with
Use CSS Counters
Use <thead> and <tbody> table elements
Use width: 0%; for the td you want really condensed in width
.tbodyCount {
counter-reset: rowIndex;
}
.tbodyCount tr {
counter-increment: rowIndex;
}
.tbodyCount td:nth-child(1)::before {
width: 0%; /* Make as smaller as possible */
content: counter(rowIndex); /* Learn about counters*/
}
<table>
<thead>
<tr>
<th>N</th>
<th>ID</th>
</tr>
</thead>
<tbody class="tbodyCount">
<tr>
<td></td>
<td>Foo</td>
</tr>
<tr>
<td></td>
<td>Bar</td>
</tr>
<tr>
<td></td>
<td>Baz</td>
</tr>
</tbody>
</table>

Updating SQL database from a dropdown using PHP script

I am just self-learning PHP and SQL. This question seems repetitive, but I cannot find exact solution for my problem.
I have a SQL database for inventory management of mobile phones. I have implemented PHP script to display the database contents in a table. I have to further enhance the script, so the user can change the status of the mobile phone such as Working or Not working. For this I have created another SQL database storing this info. I am able to display the details in a dropdown, but when I change from Working to Not working and select Submit button, no change is seen in the database and also in the web server.
<?php
$servername="localhost";
$username="root";
$password="XXXXX";
$dbname="inventory_db";
//Connection
$conn =mysqli_connect($servername,$username,$password);
$db_handle = $conn->select_db($dbname);
//Connection check
if($conn->connect_error)
{
die("Connection failed:" .$conn->connect_error);
}
else {
echo "connection setup";
}
if($db_handle)
{
$sql="SELECT asset_no,asset_name,current_holder,location,status FROM Phone_table ";
$sql_status="SELECT idstatus,status_name FROM status_table";
?>
<!DOCTYPE html>
<HTML>
<HEAD>
<STYLE>
.asset_table
{
width: 100%;
border :1px solid black;
}
td{
text-align: left;
padding: 15px;
border: 1px solid black;
}
th{
border: 1px solid black;
}
</STYLE>
</HEAD>
<BODY>
<form method="post">
<TABLE class="asset_table">
<TR>
<TH>Asset Number</TH>
<TH>Asset Name</TH>
<TH>Asset Holder</TH>
<TH>Location</TH>
<TH>Status</TH>
</TR>
<?php
$result=$conn->query($sql);
$count=mysqli_num_rows($result);
if($result->num_rows > 0)
{
while($row=$result->fetch_assoc())
{?>
<TR>
<TD> <?php echo $row['asset_no']; ?> </TD>
<TD> <?php echo $row['asset_name']; ?></TD>
<TD> <?php echo $row['current_holder']; ?></TD>
<TD> <?php echo $row['location']; ?></TD>
<TD><select>
<?php
<!-- *****This is where I am stuck*****-->
$result_status=$conn->query($sql_status);
if($result_status->num_rows > 0)
{
while($row_status=$result_status->fetch_assoc())
{ ?>
<option value =' <?php echo $row_status['idstatus']?> '>
<?php echo $row_status['status_name'];?> </option>
<?php $row['status']=$row_status['status_name'];
}} ?></select>
</TD>
</TR>
<?php
}}?>
<input type="submit">
</form>
<?php
if($submit)
{
for($i=0;$i<$count;$i++)
{
$sql="UPDATE Phone_table SET status='$status[$i]' WHERE asset_no='$asset_no[$i]'";
$result=$conn->query($sql);
}
}
?>
</TABLE>
</BODY>
</HTML>
<?php }
ob_end_flush(); ?>
One problem with the existing code is that there was no way to relate the submitted value for the asset status ( even if it had been given a name! ) to the particular record in the database. The update statement would require, usually, an ID in the where clause so that the releveant record can be updated as opposed to ALL records being updated equally. To that end, given the HTML structure and generaly approach ( no javascript & single form ) using a hidden input field for each row in the table to hold the record ID seems to make sense. When the form is submitted the value for the select menu and the id should be relatable - you will see by the demo below.
Because there is a single form with multiple records the select menu and the hidden input will need to be treatable as arrays - that is to say their names should be of the form name[]
Another thing to note perhaps is the use of variables directly within the sql. This practise leaves your code vulnerable to sql injection and whilst this may be on a closed system somewhere with trusted users etc you never know what might happen!
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
/* connect to the db */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'inventory_db';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* declare the sql statements for later use */
$sql=(object)array(
'phones' => 'select `asset_no`, `asset_name`, `current_holder`, `location`, `status` from `phone_table`',
'status' => 'select `idstatus`, `status_name` from `status_table`',
'update' => 'update `phone_table` set `status`=? where asset_no=?'
);
/* very basic utility function to generate select menu */
function createselect( $name, $data, $value ){
$html=array();
$html[]=sprintf( '<select name="%s">', $name );
foreach( $data as $id => $status ){
$selected = $id == $value ? ' selected=true' : '';
$html[]=sprintf('<option value="%s"%s>%s', $id, $selected, $status );
}
$html[]='</select>';
return implode( PHP_EOL, $html );
}
/* query database to get possible status values which are used to create the SELECT menus */
$status=array();
$results=$db->query( $sql->status );
if( $results ){
while( $rs=$results->fetch_object() )$status[ $rs->idstatus ]=$rs->status_name;
}
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* using `user supplied data` - use a prepared statement to be safe! */
$stmt=$db->prepare( $sql->update );
$stmt->bind_param( 'ii', $assetstatus, $assetid );
/* Perform the update */
foreach( $_POST['id'] as $i => $assetid ){
$assetstatus = $_POST['status'][ $i ];
$stmt->execute();
}
$stmt->close();
exit( header( 'Location: ?db=updated' ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Asses or Assets?</title>
<style>
body{font-family:verdana}
table{ width: 100%; border :1px solid black; }
td{ text-align: left; padding: 15px; border: 1px solid black;text-align:center; }
th{ border: 1px solid black; }
input,select{padding:1rem;width:100%}
</style>
</head>
<body>
<?php
/* get the phones... no user input so no need for prepared statement */
$results = $db->query( $sql->phones );
if( $results ){
?>
<form method='post'>
<table>
<thead>
<tr>
<th>Asset Number</th>
<th>Asset Name</th>
<th>Asset Holder</th>
<th>Location</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
while( $rs = $results->fetch_object() ){
printf(
"<tr>
<td>%s<input type='hidden' name='id[]' value='%d' /></td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>",
$rs->asset_no,
$rs->asset_no,
$rs->asset_name,
$rs->current_holder,
$rs->location,
createselect( 'status[]', $status, $rs->status )
);
}
?>
</tbody>
<tfoot>
<tr>
<td colspan=5>
<input type='submit' />
</td>
</tr>
</tfoot>
</table>
</form>
<?php
}//close `if`
?>
</body>
</html>
In general the form creation/display and the acting upon the submitted form are two entirely unrelated HTTP requests.
You have to change a few things to get your script to work:
1. Add a hidden field for each asset no.:
<TD>
<input type="hidden" name="asset_no[]" value="<?php echo $row['asset_no']; ?>">
<?php echo $row['asset_no']; ?>
</TD>
2. Add name attribute to your select fields:
<TD><select name="asset_status[]">
3. Make your select fields preselect the current status and remove the whitespace in the value:
<option value ='<?php echo $row_status['idstatus'] ?>' <?= $row['status'] == $row_status['idstatus'] ? ' selected' : '' ?>>
4. Remove this statement, as it does nothing (you're not writing to the array you read from the database):
$row['status']=$row_status['status_name'];
5. Add a name property to your submit field:
<input type="submit" name="submit">
6. Read your submitted form from the superglobal array $_POST (see php.net):
if(isset($_POST['submit']))
{
for($i=0;$i<count($_POST['asset_no']);$i++)
{
$asset_status = mysqli_real_escape_string($conn, $_POST['asset_status'][$i]);
$asset_no = mysqli_real_escape_string($conn, $_POST['asset_no'][$i]);
$sql = "UPDATE Phone_table SET status='$asset_status' WHERE asset_no='$asset_no'";
$result = $conn->query($sql);
}
}

Php I can't delete a row of a table

I can't delete a row that I choose with the input delete. I think that I have to set other parameters in the querydelete but i dont know exactly what.
Can anyone help me because Im a beginner? Is there another way to do something like that?
My purpose is to push the delete input and then delete the customer with the specific id (in the same raw with the delete input).
Can anyone give me a link with an example?
<!DOCTYPE html>
<html>
<head>
<title>Table with database</title>
<style>
table {
border-collapse: collapse;
width: 100%;
color: #588c7e;
font-family: monospace;
font-size: 25px;
text-align: left;
}
th {
background-color: #588c7e;
color: white;
}
tr:nth-child(even) {background-color: #f2f2f2}
</style>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>Room</th>
<th>Name</th>
<th>Check In</th>
<th>Check Out</th>
</tr>
<?php
include('db_connection.php');
$conn = OpenCon();
//SQL query
$query = "Select * from ergazomenos";
if(isset($_POST['delete'])){
$querydelete = "delete from ergazomenos where trim(ID)
='$_POST[hidden]'";
$queryexee = mysqli_query($conn, $querydelete);
}
$result = mysqli_query($conn, $query);
if (!$result){
echo("Error description: " . mysqli_error($conn));
}
//query database
while($rows = mysqli_fetch_array($result)){
$ID = $rows['ID'] ;
$Room = $rows['Room'] ;
$Name = $rows['Name'];
$CheckIn = $rows['Check In'] ;
$CheckOut = $rows['Check Out'] ;
//echo "</td><td>" . $ID. "</td><td>" "<input type=hidden ID=hidden
value=" . $rows['ID'] . $Room. "</td><td>". $Name. "</td><td>" . $CheckIn. "
</td><td>" . $CheckOut. "</td><td>";
echo "</td><td>" . $ID. "</td><td>" . $Room. "</td><td>". $Name.
"</td><td>" . $CheckIn. "</td><td>" . $CheckOut. "</td><td>";
</td>";
echo ("<form action=delete.php method=post>");
echo ("<tr><td><div align=\"center\"> $ID </div>" . "<input
type=hidden name=hidden value=".$rows['ID'] . "</td> <td><div
align=\"center\">
$Room </div></td> <td><div align=\"center\"> $Name </div></td> <td><div
align=\"center\"> $CheckIn </div></td> <td><div align=\"center\"> $CheckOut
</div></td> <td><div align=\"center\"> <td><div ");
echo ("<td>" . "<input type=submit name=delete value=delete" . "
</td>");
//
echo ($rows['ID']);
//echo '<td><input type="button" name="delete"
value="delete"></td>';
echo ("</tr>");
echo ($_POST['hidden']);
}
CloseCon($conn);
?>
</table>
<button type="button" onclick="alert('Hello world!')">Insert</button>
<button type="button" onclick="alert('Hello world!')">Update</button>
</body>
</html>
You should using prepare statement to prevent SQL injection
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$id = $_POST['hidden'];
// if you are using ID, make sure variable is number
if (is_numeric(id)) {
delete from ergazomenos where trim(ID)
='$_POST[hidden]'
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "DELETE FROM ergazomenos WHERE trim(ID) = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $id);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
}
?>
it's more secure this way.
Try with changing the $querydelete from:
$querydelete = "delete from ergazomenos where trim(ID)
='$_POST[hidden]'";
to
$querydelete = "delete from ergazomenos where trim(ID)=". $_POST['hidden'];
This should help. I didn't test the code, tho.
You have to use (single or escaped double) quotes for the attribute values in your input tag/s:
<input type='hidden' name='hidden' [etc.]
Sharing my style.
Create a column in grid named Action and along each db driven record.
<td>
Delete
</td>
In delete.php file:
include('connection.php');
$id = $_GET['id'];
$query= "delete from table where id = '$id'";
mysqli_query($conn, $query); // or $dbConn->query($query);
Redirect to grid page.

How to display error message when nothing matches with the database?

This is my code. But I have a problem.
if ($kundevor!="" or $kundenach!="")
{
if ($kundevor=="")
{
$kundezusatz=" WHERE Nachname LIKE '$kundenach%'";
}
else if ($kundenach=="")
{
$kundezusatz=" WHERE Vorname LIKE '$kundevor%'";
}
else
{
$kundezusatz=" WHERE (Vorname LIKE '$kundevor%') OR (Nachname LIKE '$kundenach%')";
}
$sql = $dbh->prepare ("SELECT Nachname, Vorname FROM tblkunden $kundezusatz ");
$sql->execute() or die("SQL Fehler in: ".$sql->queryString." <br /> ".$sql->errorInfo()[2]);
echo "<table>";
echo '<p class="abfrage2">Abfrage 3:</p>';
echo"<tr><th>Nachname</th><th>Vorname</th></tr>";
while($ds = $sql->fetch())
{
echo "<tr><td>$ds[Nachname]</td><td>$ds[Vorname]</td></tr>";
}
}
If someone for example types a letter into my form which is neither like the "Vorname" (= first name) nor like the "Nachname" (= last name) it displays nothing. But I want to have a message like "Sorry, but none of your letters match with the Names in the database".
How can you achieve that in this code?
A remark: Your statement preparation is wrongly applied and looses its purpose: to avoid sql injection. No values should be directly passed into the sql statement. Instead, parameter markers (named or not) should be defined in the statement - as placeholders. For each of these markers the corresponding value must be passed either by calling the bindValue method, or the bindParam method, or by defining it as an element value in an array passed directly as argument to the PDOStatement::execute method.
Some suggestions:
You might also want to read this and this articles on how to apply error/exception handling and this article on applying prepared statements.
Avoid creating html code from PHP. Separate the php code from the html code.
Instead of mixing db fetching code with html code (like you did with while($ds = $sql->fetch()){...}), you should fetch all db data into an array (in the php code part) and iterate through it further (in the html code part).
Below is a code version in which I implement a solution to your task/question. I used my own naming/coding conventions (inclusive for the db table) though - so, as I would apply them in my own project.
Since you didn't specified which library you are using (PDO or mysqli) and because only PDO has the PDOStatement::errorInfo method, I deducted that you are using the PDO library. Therefore, my code uses PDO.
kunden.php
<?php
require 'connection.php';
if (isset($_POST['submit'])) {
$nachname = isset($_POST['nachname']) ? $_POST['nachname'] : '';
$vorname = isset($_POST['vorname']) ? $_POST['vorname'] : '';
if (empty($nachname) && empty($vorname)) {
$errors[] = 'Please provide either the first name, or the last name, or both.';
}
if (!isset($errors)) {
// Array used for creating the WHERE conditions in the sql statement.
$whereConditions = [];
/*
* Used for injecting the proper values for the named parameter markers found
* in the sql statement. It is passed as argument to the PDOStatement::execute method.
*/
$inputParameters = [];
if (!empty($nachname)) {
$whereConditions[] = 'nachname LIKE :nachname';
$inputParameters[] = '%' . $nachname . '%';
}
if (!empty($vorname)) {
$whereConditions[] = 'vorname LIKE :vorname';
$inputParameters[] = '%' . $vorname . '%';
}
$sql = sprintf(
'SELECT kunde_id, nachname, vorname FROM kunden WHERE %s'
, implode(' OR ', $whereConditions)
);
$statement = $connection->prepare($sql);
$statement->execute($inputParameters);
$kunden = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!$kunden) {
$errors[] = 'No clients found for your request.';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nachname').focus();
});
</script>
<style type="text/css">
body {
padding: 30px;
}
label {
/*display: block;*/
font-weight: 400;
}
input[type="text"] {
display: block;
margin-bottom: 20px;
}
button {
display: block;
padding: 7px 10px;
background-color: #8daf15;
color: #fff;
border: none;
}
.messages {
margin-bottom: 20px;
}
.messages .error {
color: #c00;
}
.kunden-list {
margin-top: 20px;
border-collapse: separate;
}
.kunden-list thead th {
padding: 10px;
background-color: #ccc;
}
.kunden-list tbody td {
padding: 10px;
}
</style>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
}
?>
</div>
<div class="form-container">
<form action="" method="post">
<label for="nachname">Nachname:</label>
<input type="text" id="nachname" name="nachname" value="<?php echo isset($nachname) ? $nachname : ''; ?>">
<label for="vorname">Vorname:</label>
<input type="text" id="vorname" name="vorname" value="<?php echo isset($vorname) ? $vorname : ''; ?>">
<button type="submit" name="submit" value="submit">
Senden
</button>
</form>
</div>
<?php
if (isset($kunden) && $kunden) {
?>
<table class="kunden-list">
<thead>
<tr>
<th>ID</th>
<th>Nachname</th>
<th>Vorname</th>
</tr>
</thead>
<tbody>
<?php
foreach ($kunden as $kunde) {
$kundeId = $kunde['kunde_id'];
$nachname = $kunde['nachname'];
$vorname = $kunde['vorname'];
?>
<tr>
<td><?php echo $kundeId; ?></td>
<td><?php echo $nachname; ?></td>
<td><?php echo $vorname; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</body>
</html>
connection.php
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'yourDb');
define('USERNAME', 'yourUser');
define('PASSWORD', 'yourPassword');
define('CHARSET', 'utf8');
/*
* Create a PDO instance as db connection to db.
*
* #link http://php.net/manual/en/class.pdo.php
* #link http://php.net/manual/en/pdo.constants.php
* #link http://php.net/manual/en/pdo.error-handling.php
* #link http://php.net/manual/en/pdo.connections.php
*/
$connection = new PDO(
sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
, USERNAME
, PASSWORD
, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
Create table syntax
CREATE TABLE `kunden` (
`kunde_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nachname` varchar(100) DEFAULT NULL,
`vorname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`kunde_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Count the rows (results) you fetch form the database.
If the count is zero then display the "no results found" message.
If there are results then take care of displaying the table header before you output the first row.
$count = 0; // This keeps track of the rows fetched
while($ds = $sql->fetch())
{
// Before the first row let's put the table header
if( $count === 0 )
{
echo "<table>";
echo '<p class="abfrage2">Abfrage 3:</p>';
echo"<tr><th>Nachname</th><th>Vorname</th></tr>";
}
// Output the row
echo "<tr><td>$ds[Nachname]</td><td>$ds[Vorname]</td></tr>";
// Update the row count
$count++;
}
// No rows/results? display the message
// Otherwise close the table
if( $count === 0 )
{
// Display "no matches" message ex:
echo "<div class='some-class'>Sorry, but none of your letters match with the Names in the database</div>";
}
else
{
echo "</table>";
}
Note that your code is unsafe as prone to sql injection.
Use Prepared Statements to inject user data into the query.
When you take user input and put it into a query after a LIKE statement then % wildcards must be escaped in the input string. See this question an the accepted answer.
Finally you should trim() $kundevor and $kundenach before using them; make sure to close the <table> html at some point, I put the code after the while loop. You have some fixes to take care of...

Alternative to using PHP-GMP to populate two column table

A page is using the PHP GNU Multiple Precision (GMP) to determine how many rows should end up in each column. While the code works, we would like to migrate the application to a new host that does not support the PHP5-GMP module. That said, what might be the best alternative to generating and populating a two column table that may not always have an even number of results? Further the table design is probably not the best so I am open to alternatives.
The code below taken from here gets us close but since it uses mysql_fetch_array, it places the items like:
a b
c d
instead of
a c
b d
Is there a way to have it display in the first example?
Newer code:
<head>
<style>
.container { width: 400px; float: left; }
.container .item { width: 50%; float: left; height: someFixedHeight; }
</style>
</head>
<?php
mysql_select_db("database",$db);
$cat= $_GET["cat"];
echo '<div class="container">';
$q = mysql_query("SELECT * FROM name WHERE Field4 = '$cat'",$db);
while ($res = mysql_fetch_array($q)){
echo '<div class="item">' . $res['Field1'] . '</div>';
}
echo '</div>';
?>
Original code:
<div id="bit-list" align="center" >
<table class="list" width="600" border="0" align="center">
<tr>
<td width="300" height="72" valign="top" border="1">
<div align="left">
<?php
$result = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
$num_rows = mysql_num_rows($result);
$d3 = gmp_div_q("$num_rows", "2", GMP_ROUND_PLUSINF);
$i = 1;
$result8 = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
while ($myrow3 = mysql_fetch_row($result8))
{
if ($i <= gmp_strval($d3))
{
echo "<p>";
echo '<a href="detail.php?';
echo 'page=';
echo "$myrow3[2]";
echo '&';
echo 'pnum=';
echo "$myrow3[6]";
echo '">';
echo "$myrow3[1]";
echo "</p>";
$i = $i + 1;
}
else
{
}
}
?>
</div></td>
<td width="300" valign="top" border="1">
<div align="left">
<?php
$result = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
$num_rows = mysql_num_rows($result);
$d4 = gmp_div_q("$num_rows", "2", GMP_ROUND_MINUSINF);
$d3 = gmp_div_q("$num_rows", "2", GMP_ROUND_PLUSINF);
$j = 1;
$result18 = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
while ($myrow3 = mysql_fetch_row($result18))
{
if ($j <= gmp_strval($d3))
{
$j=$j+1;
}
else
{
echo "<p>";
echo '<a href="detail.php?';
echo 'page=';
echo "$myrow3[2]";
echo '&';
echo 'pnum=';
echo "$myrow3[6]";
echo '">';
echo "$myrow3[1]";
echo "</p>";
$j = $j + 1;
}
}
?>
</div>
</td>
</tr>
</table>
</div>
If i read well, you use gmp_div_q for rounding only? Then, you should check round().
The only case, that round() cannot cover is GMP_ROUND_ZERO, but you don't use that (and you could cover it with a simple if).

Categories