SQL PHP HTML ASP JavaScript articles and free scripts to download
 

PDO inserting recrod to MySQL table

By will learn how to insert or add record to a MySQL table by using PDO in PHP. Here we will only work on the database query and record insert part. The detail of singup page is shown here. php_signup.php

LastInsertID

This gives you the value of the auto increment Id field. The value is created once a new record is added to the table. You can read more on this at mysql_insert_id() . WE assume that the PHP Pdo connection is already available. WE will directly go to query part.

$sql=$dbo->prepare("insert into pdo_admin(userid,password,name,status) values(:userid,:password,:name,:status)");
$sql->bindParam(':userid',$userid,PDO::PARAM_STR, 15);
$sql->bindParam(':password',$password,PDO::PARAM_STR, 15);
$sql->bindParam(':name',$name,PDO::PARAM_STR,25);
$sql->bindParam(':status',$status,PDO::PARAM_STR);
if($sql->execute()){
$mem_id=$dbo->lastInsertId();
echo " Thanks .. Your Membership id = $mem_id ";
}
else{
echo " Not able to add data please contact Admin ";
}

Printing the error message.

The above code there is a if else condition checking, in case of failure of insert query it will display a message saying 'Not able to add data please contact Admin' however it does not tell about the error or mistake in the syntax. So to get more meaning full information from the database we have to use errorinfo() function. We will modify the part of the above code like this.

if($sql->execute()){
$mem_id=$dbo->lastInsertId();
echo " Thanks .. Your Membership id = $mem_id ";
}
else{
echo " Not able to add data please contact Admin ";
print_r($sql->errorInfo());
}

Download MySQL dump file to create your table to use this tutorial


Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked

Join Our Email List
Email:  
For Email Newsletters you can trust
PDO
PHP Sections