0

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

2
  • 1
    This code is confusing me, both mysql functions and OO mysqli? Commented Dec 10, 2014 at 16:57
  • To show only the first record you can add a LIMIT 1 to mysql query. To show only one id you need to add a variable to the query and populate it. Commented Dec 10, 2014 at 16:57

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

5 Comments

You'd wanna include here that the query should have a WHERE clause and should be limitted by 1, ensuring that actually one result is returned. then the if should also be changed to if($result->num_rows == 0).
Thanks, this worked great. But One more thing I needed, I want to put a plain black border around the results, similar to what you can do with CSS p.one { border-style: solid; border-width: 5px; }
So insert inside a div & can use style="border: 5px solid #aaa;".
Hello, I hate to seem really stupid, but when I try this using the <div "style="border: 5px solid #aaa;"> </div> It comes up with a syntax error Unexpected "<"
It should be <div style="border: 5px solid #aaa;"> </div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.