Adding Data to mySql - php

I have a form and trying to insert data to the mysql database. but it always jump into the error.
Same database connection working fine to view data already in the database.
Database Connection for the page stored in a separate file :
<?php
$host ="localhost";
$user = "CENSORED";
$password = "CENSORED";
$link = mysql_connect($host,$user,$password) or die("An error occurred while connecting...");
//Database Selection
$dbname="CENSORED";
mysql_select_db($dbname);
?>
HTML Form
<form action="add_admin.php" method="post">
<table>
<tr>
<td>Email Address :</td>
<td><input id="admin_email" name="admin_email" type="text" size="20"</></td>
</tr>
<tr>
<td>Name :</td>
<td><input id="admin_name" name="admin_name" type="text" size="20"</></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input id="admin_mobile" name="admin_mobile" type="text" size="12"</></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea id="admin_address" name="admin_address" rows="4" cols="50"/> </textarea></td>
</tr>
<td>Password :</td>
<td><input id="admin_pw" name="admin_pw" type="text" size="20"</></td>
</tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
PHP Code
<?php
$admin_email=$_POST['admin_email'];
$admin_name=$_POST['admin_name'];
$admin_mobile=$_POST['admin_mobile'];
$admin_address=$_POST['admin_address'];
$admin_password=$_POST['admin_password'];
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
if( mysql_query($link,$sql))
{
echo "Records Added";
}
else
{
echo "ERROR";
mysql_error($link);
}
mysql_close($link);
?>
Thanks in advance.

you have to include your Database connection file which you have kept as separate file in your php file.
<?php
include("dbconnection filename.php"):// this line.
$admin_email=$_POST['admin_email'];
$admin_name=$_POST['admin_name'];
$admin_mobile=$_POST['admin_mobile'];
$admin_address=$_POST['admin_address'];
$admin_password=$_POST['admin_password'];
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
if( mysql_query($link,$sql))
{
echo "Records Added";
}
else
{
echo "ERROR";
mysql_error($link);
}
mysql_close($link);
?>

Change to this
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('".$admin_email."','".$admin_name."','".$admin_mobile."','".$admin_address."','".$admin_password."')";

use mysql_real_escape_string
$admin_email=mysql_real_escape_string($_POST['admin_email']);
$admin_name=mysql_real_escape_string($_POST['admin_name']);
$admin_mobile=mysql_real_escape_string($_POST['admin_mobile']);
$admin_address=mysql_real_escape_string($_POST['admin_address']);
$admin_password=mysql_real_escape_string($_POST['admin_password']);

You have problems with connecting to a database. I don't like your approach to of connecting to a database so i'll provide mine approach (which works so far).
Your database config should look like
class DataBaseClass{
public $_host = "localhost";
public $_user = "X32284679";
public $_database = "X32284679";
public $_pass = "X32284679";
function connectToDatabase(){
$conn = new mysqli($this->_host, $this->_user, $this->_pass, $this->_database);
$conn->set_charset("utf8");
return $conn;
if(! $conn) {
echo "Problems with connecting to database!";
exit;
}
}
}
Later on in some other code you use this file like this
require('nameOfFile.php');
$db = new DataBaseClass();
$mysqli=$db->connectToDatabase();
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
if($rs = $mysqli->query($sql)) {
//inserted
else {
//not inserted
$mysqli->close();
}
And so on, try this approach and see if it helps you.

In your PHP page you should include your connection file:
require_once('yourdbconnection.php');
And change $_POST['admin_password'] to $_POST['admin_pw'] according to your HTML.
HTML
<form action="add_admin.php" method="post">
<table>
<tr>
<td>Email Address :</td>
<td><input id="admin_email" name="admin_email" type="text" size="20"></td>
</tr>
<tr>
<td>Name :</td>
<td><input id="admin_name" name="admin_name" type="text" size="20"></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input id="admin_mobile" name="admin_mobile" type="text" size="12"></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea id="admin_address" name="admin_address" rows="4" cols="50"> </textarea></td>
</tr>
<td>Password :</td>
<td><input id="admin_pw" name="admin_pw" type="text" size="20"></td>
</tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
PHP
<?php
require_once('yourdbconnection.php');
$admin_email=$_POST['admin_email'];
$admin_name=$_POST['admin_name'];
$admin_mobile=$_POST['admin_mobile'];
$admin_address=$_POST['admin_address'];
$admin_password=$_POST['admin_pw'];
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
mysqli_query($link, $sql) or die("Error: " . mysqli_error($link));
mysqli_close($link);
?>
This works for me. If it doesn't for you then:
Check if query columns match table columns
Check if you are using the right database and the right table
Check if you are checking result on the right database and the right table
Hope this helps!
EDIT
NOTE: I highly suggest you to switch from mysql to mysqli since mysql is now deprecated.

As you asked me to help out in one of my previous answers i decided to do some fancy stuff with this code :)
Remember, the db rows need to be named the same as your form name="name" for this to work!
db_connect.php:
$dbhost = ""; // this will ususally be 'localhost', but can sometimes differ
$dbname = ""; // the name of the database that you are going to use for this project
$dbuser = ""; // the username that you created, or were given, to access your database
$dbpass = ""; // the password that you created, or were given, to access your database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('An error occured while connecting to: '. $dbhost.' as: '.$dbuser);
mysql_select_db($dbname, $conn) or die('Sorry, an error occured when selecting the database: '.$dbname);
form.php:
<form action="add_admin.php" method="post">
<table>
<tr>
<td>Email Address :</td>
<td><input id="admin_email" name="admin_email" type="text" size="20"</></td>
</tr>
<tr>
<td>Name :</td>
<td><input id="admin_name" name="admin_name" type="text" size="20"</></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input id="admin_mobile" name="admin_mobile" type="text" size="12"</></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea id="admin_address" name="admin_address" rows="4" cols="50"/> </textarea></td>
</tr>
<td>Password :</td>
<td><input id="admin_pw" name="admin_pw" type="text" size="20"</></td>
</tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
add_admin.php:
include 'db_connect.php'; //include connection
//Why add all post thingys when you can do it dynamically ?
$i = count($_POST);
$e = 0;
//Do a foreach loop on all POSTS coming in to this file..
foreach($_POST as $Key => $Value){
//Add commas behind everything :)
if($e++ < $i - 1){
//Escaping all the strings:
$Rows .= mysql_real_escape_string($Key).", ";
$Values .= "'".mysql_real_escape_string($Value)."', ";
}
//if its the last one, dont add a comma behind!
else{
//Still escaping all the strings:
$Rows .= mysql_real_escape_string($Key);
$Values .= "'".mysql_real_escape_string($Value)."'";
}
}//end foreach loop
//Insert etc etc...
$sql = mysql_query("INSERT INTO admin($Rows) VALUES($Values)");
//If successful:
if(mysql_query($conn, $sql)){
echo "Records added.";
}
//Error ?
else{
echo "Sorry, an error occured while inserting to: ".$Rows;
echo "<br/>";
mysql_error($conn);
}
//Close connection:
mysql_close($conn);

Related

how do fetching and then inserting from multi check boxes in php

I am going to fetching table values in a html table along checkbox in each row and then inserting values in another database table from multi check boxes in php.
Only the values of checked boxes should be submitted to that table.
db name "laboratory":
test: fetching values.
package: inserting table.
view
Status
Active
Inactive
<?php
$conn=mysqli_connect("localhost","root","","laboratory") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
Please try to follow this code and implement in your program . Hope that this will cooperate you much
if(isset($_POST['name'])){
$name = $_POST['name'];
$status = $_POST['status'];
if(empty($name) || empty($status)){
echo "Field Must Not be empty";
} else{
$conn=new mysqli("localhost","root","","test");
if($conn){
$query = "SELECT * FROM userdata limit 5";
$stmt = $conn->query($query);
$val = '<form action="" method=""> ';
$val .= '<table> ';
if ($stmt) { ?>
<form action="" method="post">
<table>
<?php while ($result=$stmt->fetch_assoc()) { ?>
<tr>
<td><?php echo $result['post']; ?></td>
<td><input value="<?php echo $result['post']; ?>" type="checkbox" name="check[]" /></td>
</tr>
<?php } ?>
<tr>
<td>Actual Price </td>
<td>Discount</td>
<td>Final Price</td>
</tr>
<tr>
<td><input type="text" name="actual"/></td>
<td><input type="text" name="discount"/></td>
<td><input type="text" name="final"/></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" id="" cols="30" rows="10"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Cancel" /></td>
</tr>
</table>
</form>
<?php }} }}?>
<?php
if(isset($_POST)){
echo "<pre>";
print_r($_POST);
echo "<pre>";
}
?>`enter code here`
First of all you have to decide that what are you using either mysqli or mysql, if you are using mysqli then you have to improve your code
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
and when you want to insert the checked data will be inserted in package table. If package table in another database then you have to give us the full detail i mean tell us the database name of package table.

Empty SQL after form submission

I've searched and searched I cannot find an answer to this
I've made a form HERE It's very basic. Somehow it's not submitting the final data. the code is
<form class="form" action="submit.php" method="post">
<table>
<tr>
<td>Team Name: </td>
<td><input type="text" name="team"></td>
</tr>
<tr>
<td>Captains xbox tag: </td>
<td><input type="text" name="cap"></td>
<tr>
<td>Captains E-mail:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Team Mates: </td>
<td><TEXTAREA name="teammates" rows="6" cols="50">
Please place each team member on a new line
</TEXTAREA><br></td>
</tr>
<tr>
<td>Sub team mates: </td>
<td><TEXTAREA name="subs" rows="2" cols="50"></TEXTAREA></td>
</tr>
</table>
<p><input type="submit"></p>
</form>
That's the form
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tournament1 (team, teammates, cap, email, subs)
VALUES ('$_POST[team]','$_POST[cap]','$_POST[email]','$_POST[teammates]','$_POST[subs]')";
if ($conn->query($sql) === TRUE) {
echo "Your team has been submitted Thankyou. You will be redirected back to the tournaments page Shortly";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
What am I doing wrong? It will connect and do something because the ID fills because of its autoincremented. everything else gets lost.
Thanks in advance guys
Kyle
So I switched it around a little for you but this should work fine..
firstly the form, I have added an isset in for you:
<form class="form" action="submit.php" method="post">
<table>
<tr>
<td>Team Name: </td>
<td><input type="text" name="team"></td>
</tr>
<tr>
<td>Captains xbox tag: </td>
<td><input type="text" name="cap"></td>
<tr>
<td>Captains E-mail:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Team Mates: </td>
<td><TEXTAREA name="teammates" rows="6" cols="50">
Please place each team member on a new line
</TEXTAREA><br></td>
</tr>
<tr>
<td>Sub team mates: </td>
<td><TEXTAREA name="subs" rows="2" cols="50"></TEXTAREA></td>
</tr>
</table>
<p><input type="submit" name="sendit"></p>
</form>
You'll notice I have changed action to action="" so it runs under its own page.
Followed next by the PHP of which I have added conditions into for you.
Add the PHP to submit.php
Please note: you can also add required at the end of each input field.
if (isset($_POST['sendit']))
{
$team = $_POST['team'];
$captain = $_POST['cap'];
$email = $_POST['email'];
$mates = $_POST['teammates'];
$sub = $_POST['subs'];
if (!empty($team))
{
if (!empty($captain))
{
if (!empty($email))
{
if (!empty($mates))
{
if (!empty($sub))
{
$sql = "INSERT INTO `tournament1` (team, teammates, cap, email, subs) VALUES ('$team', '$mates', '$captain', '$email', '$sub')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Please add subs..";
}
} else {
echo "Please add mates..";
}
} else {
echo "Please add captains email..";
}
} else {
echo "Please add captains name..";
}
} else {
echo "Please add team name..";
}
}

my INSERT INTO is not working in PHP page but working in SQL

i have here a page for the registering a crew but i dont know what seems to be the problem. the query is working in phpmyadmin but not working in php page.
here is my code:
session_start();
require 'config.php';
if (#$_SESSION['username']) {
if (isset($_POST['first_name'])&&isset($_POST['middle_name'])&&isset($_POST['last_name'])&&isset($_POST['age'])&&isset($_POST['birth_date'])&&isset($_POST['birth_place'])&&isset($_POST['gender'])&&isset($_POST['martial_status'])&&isset($_POST['religion'])&&isset($_POST['nationality'])&&isset($_POST['email'])&&isset($_POST['address1'])&&isset($_POST['address2'])&&isset($_POST['course'])&&isset($_POST['school'])&&isset($_POST['remarks'])) {
$first_name = $_POST['first_name'];
$middle_name = $_POST['middle_name'];
$last_name = $_POST['last_name'];
$age = $_POST['age'];
$birth_date = $_POST['birth_date'];
$birth_place =$_POST['birth_place'];
$gender = $_POST['gender'];
$martial_status = $_POST['martial_status'];
$religion = $_POST['religion'];
$nationality = $_POST['nationality'];
$email = $_POST['email'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$course = $_POST['course'];
$school = $_POST['school'];
$remarks = $_POST['remarks'];
$date_added = date('Y-m-d');
if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
else {
echo 'Some field is empty';
}
}
echo '<!DOCTYPE html>
<html>
<head>
<title>Add New Crew</title>
</head>
<body>
<form action="add_crew.php" method="POST">
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="first_name" ></input>
</td>
</tr>
<tr>
<td>
Middle Name:
</td>
<td>
<input type="text" name="middle_name" ></input>
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<input type="text" name="last_name" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Age:
</td>
<td>
<input type="text" name="age" ></input>
</td>
</tr>
<tr>
<td>
Birth Date:
</td>
<td>
<input type="text" name="birth_date" ></input>
</td>
</tr>
<tr>
<td>
Birth Place:
</td>
<td>
<input type="text" name="birth_place" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Gender:
</td>
<td>
<input type="text" name="gender" ></input>
</td>
</tr>
<tr>
<td>
Martial Status:
</td>
<td>
<input type="text" name="martial_status" ></input>
</td>
</tr>
<tr>
<td>
Religion:
</td>
<td>
<input type="text" name="religion" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Nationality:
</td>
<td>
<input type="text" name="nationality" ></input>
</td>
</tr>
<tr>
<td>
Email Address:
</td>
<td>
<input type="text" name="email" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Address 1:
</td>
<td>
<input type="text" name="address1" ></input>
</td>
</tr>
<tr>
<td>
Address 2:
</td>
<td>
<input type="text" name="address2"></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Course:
</td>
<td>
<input type="text" name="course" ></input>
</td>
</tr>
<tr>
<td>
School Graduated:
</td>
<td>
<input type="text" name="school" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Remarks:
</td>
<td>
<input type="text" name="remarks"></input>
</td>
</tr>
</table><br>
<input type="submit" value="Submit"></input>
</form>
</body>
</html>';
}
else { header('Location: /practice1/index.php');
}
?>
this is the entire page of php
Just like Saty say you forget to insert query
$conn->query($query); // PDO for new php7
mysql_query($query,$conn); // for old code but this is deprecated
//$conn is mysql_connect in config.php (it's may be in another variable up on your write)
<?php if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status)
VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
// for mysqli code starts
mysqli_query($con, $query);
// for mysqli code ends where $con is connection variable
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
?>
you have to fire the query to insert in database , i think you forgot
add this code after your query to execute it
if (mysqli_query($conn,$query)) {
echo 'Your request is sent to queue';
}
else {
echo 'Something went wrong';
}
I think you missed Two points
1.connection between your php and mysql.
2.Firing the query.
Try with this snippet.
$username = "your_name";
$password = "your_password";
$dbhost = "localhost";
$conn = mysql_connect($dbhost, $username, $password);
//connection to the database
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
and then put
if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
After that fire your query
if (mysqli_query($conn,$query))
{
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
else
{
echo 'Some Syntax is wrong';
}
}
else {
echo 'Some field is empty';
}
And close the connection after used by
mysql_close($conn);
#prakash above is the closest to correct...
however, i think, set all of your inputs on your html with value="", so that you do not have to do all of the if(!empty() garbage and get blanks later...
$username = "your_name";
$password = "your_password";
$dbhost = "localhost";
$dbname = "your_db";
// just good practice to specify the db, later you may have multiple on the same server..
// use mysqli as someone else above stated...
$conn = mysqli_connect($dbhost, $username, $password,$dbname);
if(!$conn){
die('Connect Error: ' . mysqli_connect_error());
//again.. mysqli.. not mysql
}
// dont kill yourself with manual entry errors for the query...
// move $_POST to a new variable and prep the array for a loop;
$data = $_POST;
// get rid of the submit variable
unset($data['submit']);
// assuming this db field is int not varchar
// and assuming birthdate field is DATE or varchar
$data['age'] = intval($data['age']);
$data['birthdate'] = date('Y-m-d',strtotime($date['birthdate']));
// would be easier to set default value NOW() for date_added column and DATETIME
// NOW() will set that field to the CURRENT_TIMESTAMP on every insert for you...
// but the way you have it, and assuming db field is DATE or varchar
$data['date_added'] = date('Y-m-d');
// Same for 'crew_status' .. field VARCHAR or ENUM... default value 'PENDING'
$data['crew_status'] = 'PENDING';
// make a string variable to fill with fields...
$fields = '';
// make a string variable to to fill with insert values....
$values = '';
// loop through $data, add each value followed by a comma to string
// no single quotes on integers where the db field is INT .... like age...
foreach($data as $key=>$val){
// this is looking for the value="" from when a user blanks an input field....
if($val == ''){
// handles blank user inputs.. db fields NOT set 'not null'..no quotes around NULL
$values .= 'NULL,';
// if the value is not blanked... look for strings and dates....
}elseif(!is_int($val)){
// real_escape_string will kill any characters that will error like ' or \
// and remove in sql injection risks .. single quotes on varchar db field vals
$values .="'".mysqli_real_escape_string($conn,$val)."',";
// if input is not blank and !is_int() must be INT...age
}else{
//no quotes on integers going into INT db fields....
$values .= $val.',';
}
// add the $key (field name) to the $fields same order as $values, comma after each
// backticks around field names...
$fields .= "`".$key."`,";
}
// we are dragging an extra comma on $fields and $values at the end of each string
// we will get them in the insert query string....splitting up the query to explain
$query = "INSERT INTO `crew_info`";
//substr off the comma $fields is dragging "," put it between ( and )
$query .= "(".substr($fields,0,-1).")";
//substr off the comma $values dragging "," put it between ( and )
$query .= " VALUES (".substr($values,0,-1).")";
//not split query might be confusing to read..query would look like...
//"INSERT INTO `crew_info`(".substr($fields,0,-1).") VALUES (".substr($values,0,-1).")"
//now insert
if(!mysqli_query($conn,$query)){
// if there is an error... let someone know!
die('ooops!...'.mysqli_error());
}else{
// if no error......
echo 'you just inserted data!!! id# = '. mysqli_insert_id($conn);
}
There is an error in your sql string. INSERT INTO table VALUES(..,..);
$query = "INSERT INTO `crew_info` VALUES (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";

Insertion of data into Database

//Connection.php
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$db = 'faculty_corner';
$link = mysqli_init();
$success = mysqli_real_connect( $link, $host, $user, $password, $db);
if ($success == TRUE) {
echo 'KUDOS !!! Connected to Database';
}
?>
//varpay.php (the page from where I want the data to be sent to db)
//insert statement: in this form I have put fid as an autoincrement and calculation = NULL as I have a view button there which lets me to go to next page 'p1.php'
<pre>
<?php
if ($_POST['submit'] == 1){
$sql = "INSERT INTO `faculty_corner`.`tabdata` (fid, `facname`, `designation`, basic, varper, varamt, appamt, calculation) VALUES (NULL, '$_POST[facname]', '$_POST[designation]', $_POST[basic], $_POST[varper], $_POST[varamt], $_POST[appamt], NULL)";
if(mysqli_query($success, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
}
?>
</pre>
<form action="varpay.php" method="post">
<table name="myTable">
<thead>
<tr>
<th style="border-top-left-radius:10px;">S.no</th>
<th>Faculty Name</th>
<th>Designation</th>
<th>Basic AMt.</th>
<th>Var %</th>
<th>Var Amt.</th>
<th>Approved Aoount.</th>
<th style="border-top-right-radius:10px;">Calculation</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center" style="width:60px;" name="fid">1</td>
<td><input name="facname" type="text" class="boxin" type="number"/></td>
<td align="center" style="width:60px;" ><input type="text" name="designation" class="boxin"/></td>
<td align="center"><input name="basic" class="boxin" type="number"/></td>
<td align="center"><input name="varper" class="boxon" type="number"/></td>
<td align="center"><input name="varamt" class="boxin" type="number" value="" /></td>
<td align="center"><input name="appamt" class="boxin" type="number" value="" /></td>
<td align="center"><input type="button" name="calculation" value="view"/></td>
</tr>
<tr><td colspan="8" align="center"><button type="submit" name="submit"> SUBMIT </button></td></tr>
</tbody>
</table>
</form>
This is my error.
First of all there is no need mentioning fid if it is an auto-increment column. Second of all you are inconsistent with using '.
Try replacing the query with this version:
$sql = "INSERT INTO `faculty_corner`.`tabdata` (facname, designation, basic, varper, varamt, appamt) VALUES ('$_POST[facname]', '$_POST[designation]', '$_POST[basic]', '$_POST[varper]', '$_POST[varamt]', '$_POST[appamt]')";
Change all post values $_POST[SomeName] to $_POST['SomeName']. You are missing ' inside square bracket [].
For auto increment, just change column fid to primary key and auto-increment in your database table. It will automatically get increment.
I've updated my code. Please have a look.
<?
$sql = "INSERT INTO `faculty_corner`.`tabdata` (`fid`, `facname`, `designation`, `basic`, `varper`, `varamt`, `appamt`, `calculation`)
VALUES (NULL, '".$_POST['facname']."', '".$_POST['designation']."', '".$_POST['basic']."', '".$_POST['varper']."', '".$_POST['varamt']."', '."$_POST['appamt']".', NULL)";
?>

fetch data from db and compare with user inputs

i am creating a code for email confirmation link. user inserted email id , n stores in db. Next time when user insert id into form, first of all it will check whether email id is already present in db or not. If y then said 'already exists' & if n then insert it into db. Initially i am inserting data into db. then i want to compare user input email is with db email id. so i dont know how i retrieve data on pg then compare it. here is my code
<html>
<body>
<form name="form" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" required pattern="[a-zA-Z]+" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" required pattern="[a-zA-Z]+" /></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="email" name="mail" required /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
<?php
include 'connection.php';
if(isset($_POST["submit"]))
{
$fname="'".trim(addslashes($_POST["fname"]))."'";
$lname="'".trim(addslashes($_POST["lname"]))."'";
$email="'".trim(addslashes($_POST["mail"]))."'";
$key="'".MD5(microtime())."'";
$to=$email;
$subject="Confirm your email id";
$message="Hello $fname
Click on below link to confirm your id.
www.vs.com/abcdefghojklmnopqrstuvwxyz.php?code=$key
";
$header="From :sneha#valencynetworks.com";
// echo $fname."<br />".$email."<br />".$to."<br />".$subject."<br />".$message."<br />".$header;
if(mail($to,$subject,$message,$header))
{
$sql="insert into confirm_emailid values($email,$fname,$lname,$key,'1')";
if(mysqli_query($con,$sql))
{
die("Check your id for confirmation".mysqli_error($con));
}
}
/*$sql1=mysqli_query($con,"select * from random_key where eid=$email");
while($row=mysqli_fetch_assoc($sql1))
{
echo $row['eid'];
}*/
$result="SELECT count(eid) as number_of_occurences FROM confirm_emailid WHERE eid = $_POST['mail']";
if ($row['number_of_occurences'] == 0) {
echo "this adresse isn't in the database, so add it !";
}
else {
echo "already in the database :(";
}
mysqli_close($con);
}
?>
</body>
</html>
The best way is to use Ajax for compare this email field with database emails.
Steps :
List item
On focusout from email field call ajax request
This ajax request fields contain user entered email
on php page its checks whether email exists o not if exists it gives false flag and if not it gives true flag.
4.From this method you can check email without page loading.
When your form is submited, you have an array $_POST.
So, you just have to select from your database the sames values : exemple :
SELECT count(id) as number_of_occurences FROM member WHERE mail_adresse = $_POST['e-mail'] ;
You fetch the data like you did other times, and just compare $row['number_of_occurences'] to 0.
if ($row['number_of_occurences'] == 0) {
this adresse isn't in the database, so add it !
}
else {
already in the database :(
}
index.php
<html>
<body>
<form name="form" method="post" action="process.php">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" required pattern="[a-zA-Z]+" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" required pattern="[a-zA-Z]+" /></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="email" name="mail" required /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
process.php
<?php
$host = "localhost";
$user = "root";
$password = "yourpass";
$database = "your database name";
// Establish server connection and select database
$dbh = mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno()) {
die('Unable to connect to database ' . mysqli_connect_error());
} else {
// run query to fetch records
// $result = mysqli_query($dbh, "SELECT email_address FROM users ");
/* fetch associative array */
$email = $_POST['mail'];
$query = "SELECT `eid` FROM `confirm_emailid` WHERE `eid` = '$email'";
$result = mysqli_query($dbh, $query); //$link is the connection
if (mysqli_num_rows($result) > 0) {
die('email already exists');
} else {
$query = mysqli_query($dbh, "insert into users(email_address) values('$email')");
echo 'data inserted succesfully';
}
}

Categories