Insert user input from textbox to Database (PHP to PHPMYADMIN using mysql) - php

How do you guys insert user input from textbox(html/php) to database (phpmyadmin) using mysql
I keep getting the error "failed to insert" is there something missing with my code.
I did search online on how to fix it but nothing is working. I think something is missing with my code and I can't pin point it.
all files below are in 1 php file named index.php
<!DOCTYPE html>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'dad_trading';
$dbconn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($db);
if (isset($_POST['submit']))
{
$Lastname = $_POST['LastName'];
$firstname = $_POST['FirstName'];
$Middlename = $_POST['MiddleName'];
$address = $_POST['Address'];
$city = $_POST['City'];
$zipcode = $_POST['ZipCode'];
$email = $_POST['email'];
$number = $_POST['number'];
$query = ("INSERT INTO customer ([LName], [FName], [MName], [Street], [City], [ZipCode], [Email], [ContactNo]) VALUES ('$Lastname', '$firstname', '$Middlename', '$address', '$city','$zipcode', '$email', '$number')");
if(mysql_query($query))
{
echo "<script>alert('INSERTED SUCCESSFULLY');</script>";
}
else
{
echo "<script>alert('FAILED TO INSERT');</script>";
}
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>sample</title>
</head>
<body>
<form action="" method = "POST">
First name:
Middle Name:
Last Name:<br>
<input name="FirstName" size="15" style="height: 19px;" type="text" required>
<input name="MiddleName" size="15" style="height: 19px;" type="text" required>
<input name="LastName" size="15" style="height: 19px;" type="text" required>
<br><br>
Email Address:<br>
<input name="email" type="text" required placeholder="Enter A Valid Email Address" style="height: 19px;" size="30"><br><br>
Home Address: <br>
<input name="Address" type="text" required placeholder="Enter your home Address" style="height: 19px;" size="30" maxlength="30"><br><br>
City:
Zipcode:
<br>
<input name="City" size="7" style="height: 19px;" type="text" required>
<input name="ZipCode" size="7" style="height: 19px;" type="text" required>
<br><br>
Telephone/Mobile Number: <br>
<input name="number" type="text" required id="number" placeholder="Mobile Number" style="height: 19px;">
<br>
<br>
<button type ="submit" name="submit" value="send to database"> SEND TO DATABASE </button>
</form>
</body>
</html>

try add the form action using server variable
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

Here's an example of code that works. From w3Schools. mysql_connect is deprecated, new mysqli works.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Having tried myself to make your code work and as a beginner not knowing it was broken, I came across a few issues using your code. I leave this out for anyone who could end up here while learning on how to insert data in a database and to anyone who could want to point out the mistakes OP made by editing this answer.

I fixed the OP for my purposes, and it worked for me. Goal was to create database entries from a web form for some testing.
<html>
<head>
<meta charset="UTF-8">
<title>sample</title>
</head>
<?php
//These $variables related to the form data html elements eg "<input
//name="City"" input name=values, case sensitive which are derived from
//the //form submit with POST type, from the form at the end of this code
//block.
if (isset($_POST['submit']))
{
$Lastname = $_POST['LastName'];
$firstname = $_POST['FirstName'];
$Middlename = $_POST['MiddleName'];
$address = $_POST['Address'];
$city = $_POST['City'];
$zipcode = $_POST['ZipCode'];
$email = $_POST['email'];
$number = $_POST['number'];
//This is the sql query to apply the form inpur field values into the
database //from the user form in the web page. There is no validation
checking, which //an example at TutorialRepublic for CRUD and php...:
https://www.tutorialrepublic.com/php-tutorial/php-mysql-crud-
application.php
//...Is really much more thorough.
$con = mysqli_connect('localhost','root','Levaral','test');
$query = "INSERT INTO customer (LastName, FirstName, MiddleName,
Address, City, Zipcode, email, number) VALUES (" . " '" . $Lastname .
"', '" . $firstname . "', '" . $Middlename . "', '" . $address . "', '" .
$city . "', '" . $zipcode . "', '" . $email . "', '" . $number . "')";
if (mysqli_query($con,$query))
{
echo "<script>alert('INSERTED SUCCESSFULLY');</script>";
}
else
{
echo "<script>alert('FAILED TO INSERT');</script>";
}
}
?>
<body>
//put html element data in a <form> so you can send the data here by POST
//type, this stumped me
//at first when I was starting.
//I guess since the form is in the same page, it is available to the PHP
//function as some default.
<form action="" method = "POST">
First name:
Middle Name:
Last Name:<br>
<input name="FirstName" size="15" style="height: 19px;" type="text" required>
<input name="MiddleName" size="15" style="height: 19px;" type="text" required>
<input name="LastName" size="15" style="height: 19px;" type="text" required>
<br><br>
Email Address:<br>
<input name="email" type="text" required placeholder="Enter A Valid Email Address" style="height: 19px;" size="30"><br><br>
Home Address: <br>
<input name="Address" type="text" required placeholder="Enter your home Address" style="height: 19px;" size="30" maxlength="30"><br><br>
City:
Zipcode:
<br>
<input name="City" size="7" style="height: 19px;" type="text" required>
<input name="ZipCode" size="7" style="height: 19px;" type="text" required>
<br><br>
Telephone/Mobile Number: <br>
<input name="number" type="text" required id="number" placeholder="Mobile Number" style="height: 19px;">
<br>
<br>
<button type ="submit" name="submit" value="send to database"> SEND TO DATABASE </button>
</form>
//This part below was just for my feedback to see if it worked by
//returning some //data from the query, as in progress to have an edit
//area
//on the same page //without affecting the original if my mind serves me
//right.
<?php
/////
mysqli_select_db($con,"customer");
$sql="SELECT * FROM customer WHERE FirstName = '".$firstname."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Email</th>
<th>Number</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo '<tr style="width:20%">';
echo '<td style="width:20%">' . $row['FirstName'] . "</td>";
echo '<td style="width:20%">' . $row['LastName'] . "</td>";
echo '<td style="width:20%">' . $row['City'] . "</td>";
echo '<td style="width:20%">' . $row['email'] . "</td>";
echo '<td style="width:20%">' . $row['number'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

Related

getting error when we get data from mysql database how correct [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
i make this submit.php for submitting the student data into database
here is code
<html>
<head>
<title>Submit Student DATA </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Submit Student Data for Verify </h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Father Name :</label>
<input type="text" name="stu_fathername" id="name" required="required" placeholder="Please Father Name"/><br /><br />
<label>Phone Number :</label>
<input type="text" name="stu_phonenumber" id="name" required="required" placeholder="+92000000"/><br /><br />
<label>Address :</label>
<input type="text" name="stu_address" id="name" required="required" placeholder="Pakistan, Punjab 0000"/><br /><br />
<label>Course Name :</label>
<input type="text" name="stu_course" id="name" required="required" placeholder="Nebosh saftey"/><br /><br />
<label>Certificate Number :</label>
<input type="text" name="stu_certificatenumber" id="name" required="required" placeholder="Enter Number"/><br /><br />
<label>Registration Number :</label>
<input type="text" name="stu_registrationnumber" id="name" required="required" placeholder="Enter Number"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="city" required="required" placeholder="Lahore"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
<?php
if (isset($_POST["submit"])) {
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "college";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO students (student_name, father_name, phone_number, student_address, student_course, student_certificatenumber, student_reg, student_email, student_city)
VALUES ('" . $_POST["stu_name"] . "','" . $_POST["stu_fathername"] . "','" . $_POST["stu_phonenumber"] . "','" . $_POST["stu_address"] . "','" . $_POST["stu_course"] . "','" . $_POST["stu_certificatenumber"] . "','" . $_POST["stu_registrationnumber"] . "','" . $_POST["stu_email"] . "','" . $_POST["stu_city"] . "')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close();
}
?>
</body>
</html>
i want to make search box where 1 text box call student Registration number. when i put student registration number and click on search then i get student data from mysql
here is search code maybe correct or wroing i dont no
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
$hostname_php_result_conn = "localhost";
$database_php_result_conn = "college";
$username_php_result_conn = "root";
$password_php_result_conn = "root";
$php_result_conn = mysql_connect($hostname_php_result_conn, $username_php_result_conn, $password_php_result_conn);
mysql_select_db($database_php_result_conn,$php_result_conn);
if(isset($_POST['submit'])) {
$student_reg = $_POST['stu_registrationnumber'];
$sql1 = mysql_query("SELECT students FROM student_reg WHERE = $stu_registrationnumber");
$row1 = mysql_num_rows($sql1);
if($row1 == 0) {
echo 'Error, ID does not exist';
} else {
header('Location: show_result.php?student_reg='.$stu_registrationnumber);
}
}
?>
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="search.php" method="post">
<input name="student_reg" type="text" id="stu_registrationnumber" />
<input type="submit" name="submit" value="search" />
</form>
</body>
</html>
and here is show_result.php page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
$hostname_php_result_conn = "localhost";
$database_php_result_conn = "college";
$username_php_result_conn = "root";
$password_php_result_conn = "root";
$php_result_conn = mysql_connect($hostname_php_result_conn, $username_php_result_conn, $password_php_result_conn);
mysql_select_db($database_php_result_conn,$php_result_conn);
$stu_reg = $_GET['stu_registrationnumber'];
$sql1 = mysql_query("SELECT * FROM students WHERE stu_registrationnumber = $stu_registrationnumber");
$row1 = mysql_fetch_array($sql1);
$student_name = $row1['student_name'];
$phone_number = $row1['phone_number'];
$student_address = $row1['student_address'];
$student_course = $row1['student_course'];
$student_certificatenumber = $row1['student_certificatenumber'];
$stu_registrationnumber = $row1['stu_registrationnumber'];
$student_email = $row1['student_email'];
$student_city = $row1['student_city'];
?>
<html>
<head>
<title>Show Results</title>
</head>
<body>
<?php
echo 'Student Name = '.$student_name.'<br />
Father Name = '.$father_name;
Phone Number = '.$phone_number;
Address = '.$student_address;
Course = '.$student_course;
Certificate Number = '.$student_certificatenumber;
Registration Number = '.$stu_registrationnumber;
E-Mail = '.$student_email;
City = '.$student_city;
?>
</body>
</html>
but i getting Error, ID does not exist but in database we have registration number already but getting error still error
You have a wrong post value.
change:
<input type="text" name="stu_registrationnumber" />
to
<input type="text" name="student_reg" />
The name if your student registration input is "stu_registrationnumber" but you are looking for "student_reg" in display.php.
Change
$student_reg = $_POST['student_reg'];
to
$student_reg = $_POST['stu_registrationnumber']

message box for duplicate items

Hi everyone iv been trying for about an hour to find a simple code which makes my "Add Contact" form check if there are no duplicates of the field "ext" but i cant seem to get it to work :(
Basically it needs to check if there is already a ext number of the same value and then give a message saying "Extension Number already exists"
<?php
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("phonebook") or die(mysql_error());
$mode = $_GET['mode'];
$checkSql="select count(id) as eCount from address";
$result = mysql_query($checkSql);
$row = mysql_fetch_assoc($result);
if($row['eCount'] == 999) {
$disable = 1;
}
switch($mode) {
case 'add':
?>
<h2>Add Contact</h2>
<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>?mode=added" method="post">
<div align="center">
<table class="searchable">
<tr><td>Extension:</td><td><div align="left">
<input type="text" name="ext" />
</div></td></tr>
<tr><td>Name:</td><td><div align="left">
<input type="text" name="name" />
</div></td></tr>
<tr><td>Department:</td><td><div align="left">
<input type="text" name="department" />
</div></td></tr>
<tr><td>Email:</td><td><div align="left">
<input type="text" name="email" />
</div></td></tr>
<tr><td>Cellphone:</td><td><div align="left">
<input type="text" name="phone" />
</div></td></tr>
<tr><td colspan="2" align="center">Back | <input name="Submit" type="submit" id="Submit" value="Add New Contact" <?php if($disable ==1){?>disabled<?php } ?>/></td></tr>
<input type="hidden" name="mode" value="added">
</table>
</div>
</form>
<?php
break;
case 'added':
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$department = $_POST['department'];
$ext = $_POST ['ext'];
$sql = "INSERT INTO address (ext, name, department ,email, phone) VALUES ('" . $ext . "','" . $name . "','" . $department . "', '" . $email . "', '" . $phone . "')";
mysql_query($sql);
header('location: ' . $_SERVER['PHP_SELF']);
break;
This should do the job
$checkSql="select count(id) as eCount from address where ext = " . $_POST['ext'];
However, you are using the deprecated version of MySQL. Consider updating to MySQLi or PDO instead.
You can also update your code to give an error message. For example:
if($row['eCount'] > 0) {
echo "Extension Number already exists";
$mode = 'add';
}
This would check to see whether or not the extension number already exists, print the error message, and display the form again.
Add this below code to below $ext = $_POST ['ext']; and i hope you close the bracket '}' of switch case if yes then remove last bracket from my solution code i hope it's helpfull for you
$check_ext ="SELECT * FROM address WHERE ext = ".$ext;
$con = mysql_connect("localhost", "root", "password") or die(mysql_error());
$checked_ext = mysqli_query($con,$check_ext);
$data_chk = mysqli_fetch_array($checked_ext, MYSQLI_NUM);
if($data_chk[0]>1)
{echo "Extension Number already exists";}
else{
$sql = "INSERT INTO address (ext, name, department ,email, phone) VALUES ('" . $ext . "','" . $name . "','" . $department . "', '" . $email . "', '" . $phone . "')";
mysql_query($sql);
header('location: ' . $_SERVER['PHP_SELF']);
}
break;
}
I didn't understand why you used switch. I didn't use it but as you mentioned i check before adding extention no and if already exist then wii give a message otherwise added as new record.
index.php
<?php
$message = '';
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("phonebook") or die(mysql_error());
if (isset($_POST['submit'])){
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$department = $_POST['department'];
$ext = $_POST['ext'];
$checkSql = "select count(id) as eCount from address where ext = " . $_POST['ext']."";
$result = mysql_query($checkSql);
$data=mysql_fetch_assoc($result);
if($data['eCount'] == 0){
// as you have check it to 999 so if you want that it should be less than or equal to 999 times only then you can check `$data['eCount']<= 999` then do entry otherwise error message
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$department = $_POST['department'];
$ext = $_POST ['ext'];
$sql = "INSERT INTO address (ext, name, department ,email, phone) VALUES ('" . $ext . "','" . $name . "','" . $department . "', '" . $email . "', '" . $phone . "')";
mysql_query($sql);
$message = "Entery has been done successfully";
$_POST = array();
}else {
$message = "Selected extension number $ext already exist";
}
}
?>
<h2>Add Contact</h2>
<form name="form1" action="" method="post">
<div align="center">
<table class="searchable">
<tr><td colspan="2"><h3><?php echo $message;?></h3></td></tr>
<tr><td>Extension:</td><td><div align="left">
<input type="text" name="ext" value="<?php if(isset($_POST['ext'])){echo $_POST['ext'];}?>" />
</div></td></tr>
<tr><td>Name:</td><td><div align="left">
<input type="text" name="name" value="<?php if(isset($_POST['name'])){echo $_POST['name'];}?>" />
</div></td></tr>
<tr><td>Department:</td><td><div align="left">
<input type="text" name="department" value="<?php if(isset($_POST['department'])){echo $_POST['department'];}?>"/>
</div></td></tr>
<tr><td>Email:</td><td><div align="left">
<input type="text" name="email" value="<?php if(isset($_POST['email'])){echo $_POST['email'];}?>"/>
</div></td></tr>
<tr><td>Cellphone:</td><td><div align="left">
<input type="text" name="phone" value="<?php if(isset($_POST['phone'])){echo $_POST['phone'];}?>" />
</div></td></tr>
<tr><td colspan="2" align="center">Back | <input name="submit" type="submit" id="Submit" value="Add New Contact"/></td></tr>
</table>
</div>
</form>

Row being added to MySQL database but no other data from the html form using PHP

The data from the form is not getting saved into the database but a row is being added, I am hosting with Go Daddy. It worked perfectly on my local but now live seems to be not working. Please find below the code I am using:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$fName = mysql_real_escape_string($_POST['fName']);
$surname = mysql_real_escape_string($_POST['surname']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$tel = mysql_real_escape_string($_POST['tel']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$email = mysql_real_escape_string($_POST['email']);
$bool = true;
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db name", $con);
$sql="INSERT INTO customer (custNo, fName, surname, postcode, tel, mobile, email, timestamp)
VALUES (NULL, '$fName','$surname','$postcode', '$tel', '$mobile', '$email', 'CURRENT_TIMESTAMP')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
} else{
echo "Successfully Registered ";
}
}
mysql_close($con)
?>
and here is the html form
<form action="insert.php" method = "post">
<fieldset>
<legend>Register</legend>
<div class="col-md-4">
<label for='fName'>Enter name:</label>
<input type= "text" name = "fName" required="required" maxlength="50"/> <br/>
</div>
<div class="col-md-4">
<label for='surname'>Enter surname:</label>
<input type= "text" name="surname" maxlength="50" required="required"/> <br/>
</div>
<div class="col-md-4">
<label for='postcode'>Enter postcode:</label>
<input type= "text" name="postcode" maxlength="7"/> <br/>
</div>
<div class="col-md-4">
<label for='tel'>Enter home no:</label>
<input type= "text" name="tel" maxlength="50" /> <br/>
</div>
<div class="col-md-4">
<label for='mobile'>Enter mobile no:</label>
<input type= "text" name="mobile" maxlength="50"/> <br/>
</div>
<div class="col-md-4">
<label for='email'>Enter email * </label>
<input type= "text" name="email" required="required"/> <br/></br>
</div>
<input type="submit" value="Register"/>
</fieldset>
</form>
First :
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
If you didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
This means the query sent to MySQL would be:
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
This would allow anyone to log in without a valid password.
To your problem !
All your variables are empty due to this fact ...
A MySQL connection is required before using mysql_real_escape_string()
otherwise an error of level E_WARNING is generated, and FALSE is
returned.
put your mysql_real_escape_string() after connect.
$con = mysql_connect("localhost","username","password");
if (!$con) { ...}
mysql_select_db("db name", $con);
//-------------- next after connect not before !!! --------
$fName = mysql_real_escape_string($_POST['fName']);
[...]
$email = mysql_real_escape_string($_POST['email']);
$bool = true;
$sql="INSERT INTO customer (...) VALUES (...)";
It may be due to the varibales.
try changing the $sql line to this
$sql = "INSERT INTO customer (custNo, fName, surname, postcode, tel, mobile, email, timestamp) VALUES (NULL, '" . $fName . "', '" . $surname . "', '" . $postcode . "', '" . $tel . "', '". $mobile . "', '" . $email . "', 'CURRENT_TIMESTAMP')";

PHP form validation with javascript alert box

Hi i am new to PHP and i am trying to submit a registration form and it works fine but the problem is that when it gives some error like username already exists or password too short in an alert box and then it reloads the form page again and the user has to fill the whole form again i want the fields that are correct to remain unchanged
here is the form page code
<!DOCTYPE HTML>
<html>
<head>
<title>Details</title>
<link rel="stylesheet" type="text/css" href="reg.css">
</head>
<body id="body">
<div id="mmw"> <span> MAP MY WAY </span></div>
<form name="reg" id="reg" method="post" action="insert.php">
<h2>Kindly fill up your Information</h2>
<p>
<input name="username" required class="name" placeholder="Type Your User name" />
<input name="password" placeholder="Type Your Password" class="name" type="password" required />
<input name="first_name" required class="name" placeholder="Type Your First name" />
<input name="last_name" required class="name" placeholder="Type Your Last name" />
<input name="email" required class="email" placeholder="Type a valid E-Mail address" />
<input name="m_no" class="name" placeholder="Type Your Mobile #"/>
<input name="v_name" required class="name" placeholder="Type Your Vahical model and name"/>
<input name="capacity" required class="name" placeholder="Seating capacity"/>
<input name="fuel_type" required class="name" placeholder="Runs on what fuel type"/>
</p>
<p>
<input name="submit" class="btn" type="submit" value="Register" />
</p>
</form>
</div>
</body>
</html>
and here is the page that is processing the data
<?php
$con = mysqli_connect("localhost", "root", "", "map_my_way");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$first_name = mysqli_real_escape_string($con, $_POST['first_name']);
$last_name = mysqli_real_escape_string($con, $_POST['last_name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$m_no = mysqli_real_escape_string($con, $_POST['m_no']);
$v_name = mysqli_real_escape_string($con, $_POST['v_name']);
$fuel_type = mysqli_real_escape_string($con, $_POST['fuel_type']);
$capacity = mysqli_real_escape_string($con, $_POST['capacity']);
$exists = mysqli_num_rows(mysqli_query($con,"SELECT * FROM members WHERE username='" . $username . "'"));
if ($exists > 0) {
echo "<script language=\"JavaScript\">\n";
echo "alert('username already exists!');\n";
echo "window.location='reg.php'";
echo "</script>";
}
if (strlen ($password) < 6){
echo "<script language=\"JavaScript\">\n";
echo "alert('password must be 6 characters');\n";
echo "window.location='reg.php'";
echo "</script>";
}
else{
// if ($password < 6) {
// echo "<script language=\"JavaScript\">\n";
// echo "alert('username already exists!');\n";
// echo "window.location='reg.php'";
// echo "</script>";
// } else{
//insert query
$sql = "INSERT INTO members (username, password, first_name, last_name, email, m_no, v_name, fuel_type, capacity)
VALUES ('$username', '$password', '$first_name', '$last_name', '$email', '$m_no', '$v_name', '$fuel_type', '$capacity')";
}
//}
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
else{
header("location:pic.php");
}
// Register $username
session_start();
$_SESSION['login'] = true;
$_SESSION['username'] = $username;
mysqli_close($con);
?>
Thanks in advance
header('Location: http://example.com/some/url'); relplace it with the javascript
also try to make a function to the escape string less typing:
function security($danger) {
mysqli_real_escape_string($con, $danger)}
simply call it with the username like $username = security($_POST['username'])

Getting "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version"

Can someone please run their eye over my coding to find why I am getting this:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
I know it will be something really simple but I can not see it.
<body>
<?php
//connect to database//
$dbc = mysql_connect("localhost", "root", "***");
if (!$dbc)
die ('Could not connect: ' . mysql_error());
//select database//
$db_selected = mysql_select_db("tafe", $dbc );
if (!$db_selected)
die ('Could not connect: ' . mysql_error());
// initialise variables to store form control values
$Name = "";
$Address = "";
$Phone = "";
$Mobile = "";
$Email = "";
if($_SERVER['REQUEST_METHOD'] == "POST") // if form has been posted
{
// initialise variables to store posted values
$ContactID = $_POST["ContactID"];
$Name = $_POST["Name"];
$Address = $_POST["Address"];
$Phone = $_POST["Phone"];
$Mobile = $_POST["Mobile"];
$Email = $_POST["Email"];
//build sql insert statement
$qry = "UPDATE contacts SET Name = '" . $Name . "', Address = '" . $Address . "', Phone = '" . $Phone . "', Mobile = '" . $Mobile . "', Email = '" . $Email . "' WHERE ContactID =" . $ContactID;
// run insert statement against database
$rst = mysql_query($qry, $dbc);
if ($rst)
{
echo "<b><font color='green'>The contact has been updated.</font></b>";
echo "</br></br>";
echo "<a href=list-contacts.php>Continue</a>";
}
else
{
echo "<b><font color='red'>Error: ". mysql_error($dbc) . "</font></b>"; //alert if contact could not be added//
}
}
else // if form has not been posted
{
// build sql statement
$qry = "SELECT * FROM contacts WHERE ContactID = " . $_GET["ContactID"];
// run select statement
$rst = mysql_query($qry, $dbc);
if ($rst)
{
$row = mysql_fetch_assoc($rst); // fetch row and place column values into respective place holder variable
$Name = $row["Name"];
$Address = $row["Address"];
$Phone = $row["Phone"];
$Mobile = $row["Mobile"];
$Email = $row["Email"];
}
else // in case of an error
{
echo "<b><font color='red'>Error: ". mysql_error($dbc) . "</font></b>";
} // end of nested else statement ?>
<form name="editcontact" method="post" action="edit-contact.php">
<table border="1" cellpadding="2">
<caption> Caption 5</caption>
<!--Name Input-->
<tr>
<td><label for="Name">Name</label></td>
<td><input type="text" name="Name" value="<?php echo $Name ?>" size="30" maxlength="50" tabindex="1"/>
</td>
</tr>
<!-- Address Input-->
<tr>
<td><label for="Address">Address</label></td>
<td><textarea name="Address" cols="45" rows="5" tabindex="2"><?php echo $Address?></textarea></td>
</tr>
<!--Phone Input-->
<tr>
<td><label for="Phone">Phone</label></td>
<td><input type="text" name="Phone" value="<?php echo $Phone ?>" size="20" maxlength="20" tabindex="3" /> </td>
</tr>
<!--Mobile Input-->
<tr>
<td><label for="Mobile">Mobile</label></td>
<td><input type="text" name="Mobile" value="<?php echo $Mobile ?>" size="20" maxlength="20" tabindex="4" /> </td>
</tr>
<!--Email Input-->
<tr>
<td><label for="Email">Email</label></td>
<td><input type="text" name="Email" value="<?php echo $Email ?>" size="30" maxlength="50" tabindex="5" /></td>
</tr>
<!--Submit Button-->
<tr>
<td colspan="2" align="center"><input type="submit" name="Submit" value="Submit" tabindex="6"/>
</td>
</tr>
</table>
</form>
<?php
} // end of main else statement
mysql_free_result($rst); //free memory//
?>
</body>
</html>`
The $_POST["ContactID"] returns null, that's why you got that error.
Send the ContactID to the server:
<input type="hidden" name="ContactID" value="<?php echo $_GET["ContactID"]; ?>" />
There are sevenal problems with your code:
Do not use the mysql_* functions. They're outdated. Use the mysqli_* or PDO.
Always check the data that was send by the user, or the user may delete your database.
Do not use <b> and <font> tags. It's 2014. Use HTML5, and CSS3.
Use htmlspecialchars(), or the user will be able to attack your site (XSS)
If you use labels, you need to set the input's id.
Do not use tables to build up the site. Use floated divs.
This code will work well:
<?php
try
{
$db = new PDO("mysql:dbname=tafe;host=localhost", "root", "***");
}
catch (PDOException $e)
{
die("Cannot connect to database.");
}
function post($name)
{
return isset($_POST[$name]) ? $_POST[$name] : "";
}
function html($x)
{
return htmlentities($x, ENT_QUOTES, "UTF-8");
}
if (post("id"))
{
$query = $db->prepare("UPDATE contacts SET Name = :name, Address = :address, Phone = :phone, Mobile = :mobile, Email = :email WHERE ContactID = :id");
$query->bindParam(":name", post("name"));
$query->bindParam(":address", post("address"));
$query->bindParam(":phone", post("phone"));
$query->bindParam(":mobile", post("mobile"));
$query->bindParam(":email", post("email"));
$query->bindParam(":id", post("id"));
if ($query->execute())
$message = '<span style="color: green; font-weight: bold;">The contact has been updated.</span><br />Continue';
else
$message = '<span style="color: red; font-weight: bold;">There was an error.</span>';
}
elseif (isset($_GET["ContactID"]))
{
$query = $db->prepare("SELECT Name, Address, Phone, Mobile, Email FROM contacts WHERE ContactID = :id");
$query->bindParam(":id", $_GET["ContactID"]);
if ($query->execute())
{
if (!$query->rowCount())
$message = '<span style="color: red; font-weight: bold;">This contact does not exists.</span>';
else
{
$row = $query->fetch(PDO::FETCH_ASSOC);
foreach ($row as $k => $v)
$_POST[$k] = $v;
}
}
else
$message = '<span style="color: red; font-weight: bold;">There was an error.</span>';
?>
<!DOCTYPE html>
<html>
<head>
<title>Contact</title>
<meta charset="utf-8" />
</head>
<body>
<?php
if (isset($message))
echo "<p>".$message."</p>";
?>
<form action="edit-contact.php" method="post">
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" value="<?php echo html(post("name")) ?>" /><br />
<label for="address">Address:</label><br />
<textarea name="address" id="address"><?php echo html(post("address")) ?></textarea><br />
<label for="phone">Phone:</label><br />
<input type="text" name="phone" id="phone" value="<?php echo html(post("phone")) ?>" /><br />
<label for="mobile">Mobile:</label><br />
<input type="text" name="mobile" id="mobile" value="<?php echo html(post("mobile")) ?>" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" value="<?php echo html(post("email")) ?>" /><br />
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="id" value="<?php echo isset($_GET["ContactId"]) ? intval($_GET["ContactId"]) : "0" ?>" />
</form>
</body>
</html>
try this
$qry = "UPDATE contacts
SET Name = '" . $Name . "',
Address = '" . $Address . "',
Phone = '" . $Phone . "',
Mobile = '" . $Mobile . "',
Email = '" . $Email . "'
WHERE ContactID = '" . $ContactID . "' " ;
and change to that query also
$qry = "SELECT * FROM contacts WHERE ContactID = '" . $_GET['ContactID']."' " ;
nB:
1- you should escape your variables by mysql_real_escape_string()
2- you should use PDO or MYSQLI instead of MYSQL
Try this
$qry = "UPDATE contacts SET
Name = '" . mysql_real_escape_string($Name) . "',
Address = '" . mysql_real_escape_string($Address) . "',
Phone = '" . mysql_real_escape_string($Phone) . "',
Mobile = '" . mysql_real_escape_string($Mobile) . "',
Email = '" . mysql_real_escape_string($Email) . "'
WHERE ContactID =" . $ContactID;
MAKE SURE in your html form you have a hidden text box or text box with name "ContactID"
Since you are using this in the query and I dont see that within the form.
$ContactID = $_POST["ContactID"];
NOTE : You are using mysql_* functions which are deprecated, start using mysqli_* functions or PDO

Categories