Bodhidarma
Bodhidarma

Reputation: 559

MYSQL/PHP outputting entire table when I only want to output one row

This is definitely a beginner's question. There are two issues. The id in my MYSQL table (set to autoincrement) keeps going up, even though I delete rows from my table (I'm using phpmyadmin). As for the other issue, I can't seem to find a way to work with the row most recently entered by the user. The code echos all existing rows from MYSQL. I've bolded the most pertinent section of code.

<?php
//establish connection to mysql
$con = mysql_connect("localhost","root","");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

/*retrieve user input from input form
and initialize variables */  
$Word1 = $_POST["Word1"];
$Word2 = $_POST["Word2"];
$Word3 = $_POST["Word3"];
$Word4 = $_POST["Word4"];
$Word5 = $_POST["Word5"];

//select db
mysql_select_db("madlibs", $con);  

//insert user input for word 1
$sql = "INSERT INTO test (Word1, Word2, Word3, Word4, Word5)
VALUES
('$Word1', '$Word2', '$Word3', '$Word4', '$Word5')";
if(!mysql_query($sql,$con))
{
  die('Error: ' . mysql_error());
}

$result = mysql_query ("SELECT * FROM test");  

/* take note here */
while($row = mysql_fetch_array($result))
{
  echo $row['Word1'] . " " . $row['Word2'] . " " . $row['Word3'] . " " . 
       $row['Word4'] . " " . $row['Word5'] . " " . $row['id'];
  echo "<br />";
} /* take note here */
mysql_close($con);
?>

Upvotes: 0

Views: 189

Answers (2)

Robin Orheden
Robin Orheden

Reputation: 2764

SELECT * FROM test ORDER BY Id DESC LIMIT 1

Upvotes: 0

Tyler Eaves
Tyler Eaves

Reputation: 13121

$result = mysql_query ("SELECT * FROM test order by id desc limit 1");

As for your id question...that's how ids work. They don't fill in gaps.

On a side note: Never ever put user submitted data directly into the query string. Always escape them with mysql_real_escape_string().

Upvotes: 2

Related Questions