Jay Wit
Jay Wit

Reputation: 3057

PHP MySQL single column/row display?


I'm trying to get a single result from my database, just one name.
I tried using;

$row = mysql_fetch_array(mysql_query("SELECT * FROM persons WHERE id = '$id'"));
echo $row['name'];

But that din't work, any other way to simply show only one result?
Thanks in advance!

[EDIT:]
(I'm using PHP 5.3)

<?php
include("connection.php");
$id = $_GET['deletid'];
$result = mysql_query("SELECT * FROM persons WHERE id = '$id' LIMIT 1");
if(!$result){
    echo mysql_error();
}
if ($row = mysql_fetch_array($result)){
    echo $row['name'];
}
echo "<p>id:$id</p>";
?>

Upvotes: 0

Views: 8755

Answers (2)

Shoe
Shoe

Reputation: 76280

If you need just the name and you need just one result you should rewrite your query as follow:

$row = mysql_fetch_array(mysql_query("SELECT name FROM persons WHERE id = '". (int) $id ."' LIMIT 1"));

Now to get the result you should just get it with a

$row['name'];

EDIT Now that you posted your entire code i got what's wrong: You are deleting that result before getting its name. Basically you delete that user and then you attempt to get its name. EDIT

<?php
include("connection.php");
    if (empty($_GET['deleteid'])) { 
        exit('"deleteid" is empty'); 
    }
$id = mysql_real_escape_string($_GET['deletid']);
$result = mysql_query("SELECT name FROM persons WHERE id = '". (int) $id ."' LIMIT 1");
    if(!$result){
        echo mysql_error();
    }
$row = mysql_fetch_assoc($result); // for just one result you don't need of any loop
echo $row['name'];

echo "<p>id:". htmlspecialchars($id) ."</p>";
?>

Upvotes: 2

xkeshav
xkeshav

Reputation: 54050

try

$row = mysql_fetch_array(mysql_query("SELECT name FROM persons WHERE id = ". (int) $id));

echo $row['name'];

Upvotes: 0

Related Questions