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>
Related
So $_POST['acc'], and $_POST['psw'] can't get data from the form for some reason, they are empty all the time.
html:
<div id="signUp_UI">
<form id="su_form" action="<?php echo url_for('/sign_up.php')?>" method="post" enctype="multipart/form-data">
YYQ<br><br>
Account Name<br>
<input type="text" placeholder="Account Name" id="an" name="acc">
<br><br>
Passward<br>
<input type="password" placeholder="Password" id="password" name="psw">
<br><br>
<input type="button" name="goback" value="Go Back" id="gb_button">
<input type="submit" value="Sign Up" id="su_button2">
</form>
</div>
php:
$an = isset($_POST['acc']) ? $_POST['acc'] : '';
$psw = isset($_POST['psw']) ? $_POST['psw'] : '';
$sql = "INSERT INTO log_in (account, password) VALUES ('". $an . "'," . "'" . $psw . "')";
$result = mysqli_query($db, $sql);
if($result){
$new_id = mysqli_insert_id($db);
redirect_to(url_for('/home.php?id=') . $new_id);
}
else{
echo mysqli_error($db);
db_disconnect($db);
exit();
}
Update:
So if I change php code to:
if(is_post_request()){
$an = isset($_POST['acc']) ? $_POST['acc'] : '';
$psw = isset($_POST['psw']) ? $_POST['psw'] : '';
$sql = "INSERT INTO log_in (account, password) VALUES ('". h($an) . "'," . "'" . h($psw) . "');";
$result = mysqli_query($db, $sql);
if($result){
echo '$an = ' . $an .'<br>';
echo '$psw = ' . $psw;
}
else{
echo mysqli_error($db);
db_disconnect($db);
exit();
}
then I got the result:
$an =
$psw =
UPDATE:
So I tried to detect isset($_POST['submit']) in php file, the result is $_POST['submit'] does not exist.
So it's like after I've submit the form, it isn't been sent to the php file for some reason.
UPDATE 3.0:
So if i change method to get, everything works find! I don't know why is that.
html:
<div id="signUp_UI">
<form id="su_form" action="<?php echo url_for('/sign_up.php'); ?>" method="get">
YYQ GameStation<br><br>
Account Name<br>
<input type="text" placeholder="Account Name" id="an" name="account">
<br><br>
Password<br>
<input type="password" placeholder="Password" id="password" name="password">
<br><br>
<input type="button" name="goback" value="Go Back" id="gb_button">
<input type="submit" name = "submit" value="Sign Up" id="su_button2">
</form>
</div>
php:
if(isset($_GET['submit']) && !empty($_GET['submit'])){
$an = isset($_GET['account'])?$_GET['account']:'';
$psw = isset($_GET['password'])?$_GET['password']:'';
$sql = "INSERT INTO log_in (account, password) VALUES ('". h($an) . "'," . "'" . h($psw) . "');";
$result = mysqli_query($db, $sql);
if($result){
redirect_to(url_for('/home.php'));
}
else{
echo mysqli_error($db);
db_disconnect($db);
exit();
}
Alright, according to sources I've found, it seems that there is something wrong with phpstrom build-in server. POST method somehow just doesn't work.
Reference ~ https://intellij-support.jetbrains.com/hc/en-us/community/posts/206999125-PhPStorm-10-does-not-allow-POST-method
Why you need to do this?
<form id="su_form" action="<?php echo url_for('/sign_up.php')?>" method="post" enctype="multipart/form-data">
Can you try to replace this
from:
action="<?php echo url_for('/sign_up.php')?>"
to:
action="sign_up.php"
I am trying to set up a form for a user to enter information and then for that information to be inserted into a SQL table. I am not getting any error messages but the table is not updating in my database.
My form page is this:
<!DOCTYPE html>
<html>
<head>
<title>Input 2</title>
</head>
<body>
<h1>Add a user</h1>
<form action="input-followup2.php" method="post">
First Name:
<br/>
<input type="text" name="firstName">
<br/>
<br>
Last Name:
<br/>
<input type="text" name="lastName">
<br/>
<br>
Email Address:
<br/>
<input type="text" name="emailAddress">
<br/>
<br>
Monthy Food Budget:
<br/>
<input type="number" step="0.01" name="foodBudget">
<br/>
<br>
Monthly Utility Budget:
<br/>
<input type="number" step="0.01" name="utilityBudget">
<br/>
<br>
Monthly Entertainment Budget:
<br/>
<input type="number" step="0.01" name="entertainmentBudget">
<br/>
<br>
<input name="Add User" type="submit" value="Submit">
</form>
</body>
The action for the form summit button links to this page:
Your input was received as:
<?php
$firstName = $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];
$emailAddress = $_REQUEST["emailAddress"];
$foodBudget = $_REQUEST["foodBudget"];
$utilityBudget = $_REQUEST["utilityBudget"];
$entertainmentBudget = $_REQUEST["entertainmentBudget"];
echo '<br/>';
echo '<br/> Name: ';
echo $firstName;
echo ' ';
echo $lastName;
echo '<br/> Email Address: ';
echo $emailAddress;
echo '<br/> Food Budget: $';
echo $foodBudget;
echo '<br/> Utility Budget: $';
echo $utilityBudget;
echo '<br/> Entertainment Budget: $';
echo $entertainmentBudget;
?>
<?php
require_once 'login.php';
$connection = mysqli_connect(
$db_hostname, $db_username,
$db_password, $db_database);
if(mysqli_connect_error()){
die("Database Connection Failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
); };
$addUser = "INSERT INTO CUSTOMER (CustomerID, CustomerFirstName, CustomerLastName, CustomerEmail,FoodBudget, UtilityBudget, EntertainmentBudget)
VALUES (001,{$connection ->real_escape_string($_POST[firstName])}, {$connection ->real_escape_string($_POST[lastName])},{$connection - >real_escape_string($_POST[emailAddress])}, {$connection ->real_escape_string($_POST[foodBudget])}, {$connection ->real_escape_string($_POST[utilityBudget])}, {$connection ->real_escape_string($_POST[entertainmentBudget])} );";
$upload = mysqli_query($connection, $addUser);
mysqli_close($connection);
?>
When I run the action, and check SELECT * FROM CUSTOMERS; the fields continue to return null. Can someone point me in the right direction?
Try
$firstName = mysqli_real_escape_string($firstName);
$lastName = mysqli_real_escape_string($lastName);
$emailAddress = mysqli_real_escape_string($emailAddress);
$foodBudget = mysqli_real_escape_string($foodBudget);
$utilityBudget = mysqli_real_escape_string($utilityBudget);
$entertainmentBudget = mysqli_real_escape_string($entertainmentBudget);
$addUser = "INSERT INTO CUSTOMER(CustomerID, CustomerFirstName, CustomerLastName, CustomerEmail, FoodBudget, UtilityBudget, EntertainmentBudget) VALUES (001, '" . $firstName . "', '" . $lastName . "', '" . $emailAddress . "', '" . $foodBudget . "', '" . $utilityBudget . "', '" . $entertainmentBudget . "')";
$addUser = "INSERT INTO CUSTOMER (CustomerID, CustomerFirstName, CustomerLastName, CustomerEmail,FoodBudget, UtilityBudget, EntertainmentBudget)
VALUES (001,{$connection ->real_escape_string($_POST[firstName])}, {$connection ->real_escape_string($_POST[lastName])},{$connection - >real_escape_string($_POST[emailAddress])}, {$connection ->real_escape_string($_POST[foodBudget])}, {$connection ->real_escape_string($_POST[utilityBudget])}, {$connection ->real_escape_string($_POST[entertainmentBudget])} );";
You are trying to call function inside double quoted string. It is not possible. You are limited to substitute variables only.
Use string catenation instead.
$addUser = "INSERT INTO CUSTOMER (CustomerID, CustomerFirstName, CustomerLastName, CustomerEmail,FoodBudget, UtilityBudget, EntertainmentBudget)
VALUES (001,'".
$connection->real_escape_string($_POST[firstName]).
"', '".
$connection->real_escape_string($_POST[lastName]).
"','".
$connection->real_escape_string($_POST[emailAddress]).
"', '".
$connection->real_escape_string($_POST[foodBudget]).
"', '".
$connection->real_escape_string($_POST[utilityBudget])}.
"', '".
$connection->real_escape_string($_POST[entertainmentBudget]).
"' );";
Even better, use prepared statements and placeholders.
Also, you can check for errors and show them if any:
if (!$connection->query($addUser)) {
printf("Error: %s\n", $connection->error);
}
You can find that table name is wrong. (because the table name is case sensitive)
Double quoted strings
Prepared statements
Are table names in MySQL case sensitive?
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>
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')";
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