1

I am creating a PHP script that checks if your database contains an element with the same name. Here's the code:

<?php

$query = @mysql_query("SELECT * FROM category");

while($Row = mysql_fetch_array($query)) {
    $ID = $Row['id'];
    $Name = $Row['name'];
}

// fetch the value of the name field
$CategoryName = $_GET['name'];

if($CategoryName === $Name) {
    echo "here is an element with the same name";
}

?>

Why doesn't it work? Where is the error? Sorry for my English, I'm Italian.

1

4 Answers 4

3

If you only want to know if the element exists or not, you can change your query to be much more efficient.

$query = mysql_query("SELECT COUNT(Name) FROM category WHERE Name = '" . mysql_real_escape_string($_GET['name']) . "'");
$row = mysql_fetch_array($query);
if ($row[0]) {
  echo "here is an element with the same name";
}
2

If there are multiple items being returned from the database, you need to wrap your logic within the while:

// fetch the value of the name field
$CategoryName = $_GET['name'];

while($Row = mysql_fetch_array($query)) {
    $ID = $Row['id'];
    $Name = $Row['name'];

    if($CategoryName === $Name) {
        echo "here is an element with the same name";
    }
}
0

Use the below code:

$query = @mysql_query("SELECT * FROM category");

$flag = false; // I am using a flag variable

// fetch the value of the name field
$CategoryName = $_GET['name'];

 while($Row = mysql_fetch_array($query)) {
    $ID = $Row['id'];
    $Name = $Row['name'];
    if($CategoryName === $Name) {
       $flag = true;
    }
}

if($flag) {
    echo "here is an element with the same name";
}
?>

This is also a trick to check the name in database.

0

I think the optimize way will be use count aggregate function in mysql to match how many rows match to your given name. This can be done in two ways.

$query = mysql_query("SELECT COUNT(Name) FROM category WHERE Name = '" .      mysql_real_escape_string($_GET['name']) . "'");
 $row = myqsl_fetch_array($query);
 if ($row[0]) {
      echo "here is an element with the same name";
   }

or by this

$query = mysql_query("SELECT Name FROM category WHERE Name = '" .      mysql_real_escape_string($_GET['name']) . "'");
 $row = mysql_num_rows($query);
 if ($row>0) {
      echo "here is an element with the same name";
 }
1
  • It does not work. I have write: $query = mysql_query("SELECT name FROM category WHERE name = '" . mysql_real_escape_string($_GET['name']) . "'"); $row = mysql_num_rows($query); if ($row>0) { echo "here is an element with the same name"; } else { $sql = "INSERT INTO category (name) VALUES ('".$_REQUEST['name']."'; } Commented Jun 7, 2013 at 5:05

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.