sameera lakshitha sameera lakshitha -3 years ago 101
MySQL Question

Search function is work but insert function isn't work in php

I want to insert & search data to database with MySQL and PHP. I used WAMP server. The search function is working correctly, but insert function is didn't work.

My table is:

enter image description here

my error in

Fatal error: Uncaught exception 'mysqli_sql_exception' with message '

PHP code is:

$host = "localhost";
$user = "root";
$password = "";
$database = "testdb";

$id = "";
$fname = "";
$lname = "";
$age = "";

$connect = mysqli_connect($host, $user, $password, $database);
catch (Exception $ex){
echo 'Error';

$data = getPosts();
$sql = "INSERT INTO users (id, fname, lname, age) VALUES ('$data[0]','$data[1],'$data[2]','$data[3]')";

$result= mysqli_query($connect,$sql);
echo 'Insert is success.....';
echo 'Insert is unsuccess';

function getPosts(){

$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['fname'];
$posts[2] = $_POST['lname'];
$posts[3] = $_POST['age'];
return $posts;

$data = getPosts();
$search_Query = "SELECT * FROM users WHERE id = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
while($row = mysqli_fetch_array($search_Result))
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
$age = $row['age'];
echo 'No Data for this id';
echo 'Result Error';

html code:

<form action="" method="post">
Enter Your Id: <input type="number" name="id" placeholder="Id" value="<?php echo $id;?>"><br><br>
Enter Your First Name: <input type="text" name="fname" placeholder="First Name" value="<?php echo $fname;?>"><br><br>
Enter Your Last Name:<input type="text" name="lname" placeholder="Last Name" value="<?php echo $lname;?>"><br><br>
Enter Your Age:<input type="number" name="age" placeholder="Age" value="<?php echo $age;?>"><br><br>
<input type = "submit" name="insert" value="Add">
<input type = "submit" name="search" value="Search">

Anyone can help me? Thanks!

Answer Source

You forgot single quote(') after $data[1] in your insert query.

Change your insert query with this:

$sql = "INSERT INTO users (id, fname, lname, age) VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."')";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download