简体   繁体   中英

Getting only one row of a mysql table displayed using PHP

I Currently have this code that displays all entries rows from a mysql table and displays them on a web page;

<?php
$servername = "localhost";
$username = "appuser1";
$password = "*****";
$dbname = "acmefg_app";

$row = mysql_fetch_array(mysql_query("SELECT jobnumber FROM appdata WHERE id = '5608' LIMIT 1"));

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, jobnumber, assetnumber FROM appdata";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<br> id: ". $row["id"].  "<br>";
         echo "<br> Job number: ". $row["jobnumber"]. "<br>";
         echo "<br> Asset number: " . $row["assetnumber"] . "<br>";
     }
} else {
     echo "0 results";
}

$conn->close();
?>  

How can I change this so it only displays one result? Lets say in this case I wanted to display the row with an id of 5611? Many Thanks

If you want to show only one row then no need to use while() loop. Remove loop

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo "<br> id: ". $row["id"].  "<br>";
    echo "<br> Job number: ". $row["jobnumber"]. "<br>";
    echo "<br> Asset number: " . $row["assetnumber"] . "<br>";
} 

Or can set LIMIT 1 in your query string.

SELECT id, jobnumber, assetnumber FROM appdata LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM