Update a database only if the name entered isnt already in the database

Movie Name: <?php $query = "SELECT * from movies WHERE name = $movieName"; $result = mysql_query($query); if ($result) { echo "$movieName is already in the database"; // $valid is just a flag to let me know that the database should not be updated. $valid = false; } ?>

ih ave tried if ($result) and if (!$result) and if ($result = false) and a few other variations, I am wanting valid to be changed to false only when it finds $movieName in the movies table.

This is not testing if $result is false, it is actually assigning false to $result!

To assign a value to a variable use =
To match a value in a variable use ==
To get an absolute match use ===

What is $movieName? Where is it set?

Before we begin, I won’t use mysql so the code i’m about to use WILL NOT copy and paste straight into your code.

Your code:

You missed out the fetch part of the query.
[php]$query = mysqli_query($q);
$result = mysqli_fetch_row($query);
// remember, if pulling more than one record, use
// mysqli_fetch_assoc or
// mysqli_fetch_array rather than row.[/php]

Hope that helps,
Red :wink:

Let me rephrase the question.

When I run a query and put it in $result, how then do I check to see if there is anything in $result

Do that by using an if statement

[php]if ($result ) {
// Data was retrieved from database table
}[/php]

Still not getting anywhere with this.

// Make sure they entered something in the movie name. If not, write error message and set $valid = false
if (empty($movieName)) {
echo “A name for the movie is required”;
$valid = false;
}
// Make sure the movie Name is not too long for the database
if (strlen($movieName) > 30) {
echo “

Movie name must be no more then 30 characters long

”;
$valid = false;
}
//Check to see if the name is already in the database
$query = “SELECT * FROM movies WHERE name = $movieName”;
$result = mysql_query($query);
if (!empty($result)) {
echo “$result is already in the database”;
$valid = false;
}

The first 2 checks work, if the $movieName is empty or has too many characters. The 3rd check where I am trying to make sure the movie is not already in the database does not work. I have tried many different variations on the IF statement but each time I try this out it will either let me put in duplicates or it will not let me put anything in at all.

You really need to ditch the obsolete Mysql code.

[php]if (count($result))
{
echo “Movie is already in the database”;
}[/php]

Thank you all for your help. I have achieved functionality.

Sponsor our Newsletter | Privacy Policy | Terms of Service