Checking if record already exist.

Hello

I made a simple PHP program to check if the record already exist it will show a message on the same page.

However it does not seems to work even the records already exist.

[php]<?php
if (isset($_POST[‘submit’]))
{
include ‘db.php’;//Connect to database
$title=$_POST[‘title’] ;
$author= $_POST[‘author’] ;
$name=$_POST[‘name’] ;
$copy=$_POST[‘copy’] ;

$title_search = mysqli_query($con,"SELECT * FROM Books WHERE Title='$title'");
if ($title_search == $title)
{
Echo 'Record already exist!';
}
	 mysql_query("INSERT INTO `books`(
	 Title,
	 Author,
	 PublisherName,
	 CopyrightYear) 
	 
	 VALUES 
	 (
	 '$title',
	 '$author',
	 '$name',
	 '$copy'
	 )"); 
    }

?>[/php]

That’s because $title_search can’t be handled like that. if all you want to do is see if something exists, just look at how many rows it returned, if it’s != 0, then it found something, else it didn’t.
[php]

<?php if(isset($_POST['submit'])) { include 'db.php';//Connect to database $title=$_POST['title'] ; $author= $_POST['author'] ; $name=$_POST['name'] ; $copy=$_POST['copy'] ; $title_search = mysqli_query("SELECT title FROM Books WHERE Title='$title'"); if(mysqli_num_rows($title_search) != 0) { echo 'Record already exist!'; } else { mysql_query("INSERT INTO `books`(Title, Author, PublisherName, CopyrightYear) VALUES ( '$title', '$author', '$name', '$copy')"); } } [/php] All you have to do is make sure how its being entered matches the case of the title since A != a (in other words, searches are case sensitive).

The code was good. There was a little modification on the cases but i works… You cannot even add existing title.

May I ask off topic question. Is it possible to place the message on the top of Submit button or any part of the page?

Thanks.

Roggie

The code richei provided is standalone and only requires the DB connection to be there (included). You can put it anywhere you like, though it’s not a good thing to in-line PHP within HTML.

May I know the good practice sebrenauld?

Separate your code into the business logic (which may or may not include MySQL operations if you can be bothered building models for your data) and the templating. This allows you to easily change the business logic (i.e. the path that your code takes) without seeing zillions of irrelevant HTML echos… and to edit the templating without having to worry about the in-line PHP.

It’s not a question of performance, but of readability :slight_smile:

Thanks sebrenauld,

I will keep that in mind.

Sponsor our Newsletter | Privacy Policy | Terms of Service