2

I want to select the last row for my database and echo the columns titled s1 and s2 to the body of the web page, the following is my code. This gives an error.

<html>
<body>
<?php

$servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydb2";

            $conn = new mysqli($servername, $username, $password, $dbname);
            if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);
            } 
$sql = "SELECT s1, s2 from reading ORDER BY id DESC LIMIT 1";
$row = array();
$row = mysqli_query($conn,$sql);
echo " cup 1". $row["s1"]. "CUP 2". $row["s2"];
 ?>



</body>
</html>
1
  • 4
    you skipped the fetch part, after the query execution, fetch the results Commented Apr 29, 2016 at 3:20

3 Answers 3

2

You have to use mysqli_fetch_assoc (that will loop through your resultset) as follows:

if ($result = mysqli_query($conn, $sql)) {

    while ($row = mysqli_fetch_assoc($result)) {
        echo " cup 1". $row["s1"]. "CUP 2". $row["s2"];
    }

    /* free result set */
    mysqli_free_result($result);
}

Without loop:

if ($result = mysqli_query($conn, $sql)) {

    $row = mysqli_fetch_assoc($result);
    if($row)
    {
       echo " cup 1". $row["s1"]. "CUP 2". $row["s2"];
    }

    /* free result set */
    mysqli_free_result($result);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why loop for just 1 row?
0

Your solution

<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb2";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("MySQL Connection Error"); // Try not to output SQL error messages on the front-end, look into error_reporting()
}

$sqlQuery = "SELECT s1, s2 from reading ORDER BY id DESC LIMIT 1";
$results = mysqli_fetch_assoc(mysqli_query($conn, $sqlQuery));
echo " cup 1". $results["s1"]. "CUP 2". $results["s2"];
?>
</body>
</html>

In addition to that, I suggest not doing your SQL operations in both procedural style and object-oriented style, as this can lead to many complications in the future.

Comments

0

Use mysqli_fetch_assoc for fetching the result to array

$sql = "SELECT s1, s2 from reading ORDER BY id DESC LIMIT 1";
if ($result = mysqli_query($conn, $sql)) {
    $row = mysqli_fetch_assoc($result);
    echo " cup 1". $row["s1"]. "CUP 2". $row["s2"];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.