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?
Related
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>
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')";
I updated code per suggestions but now it only sends name to DB and sends phone number to email field. I have copied new code below.
Form:
<form action="processor.php" method="post">
<div class="field-box">
<label>Name:</label>
<input type="text" name="name" />
</div>
<div class="field-box">
<label>Age:</label>
<input type="text" name="age" />
</div>
<div class="field-box">
<label>Phone Number:</label>
<input type="text" name="phone" />
</div>
<div class="field-box">
<label>Email:</label>
<input type="text" name="email"/>
<input type="submit">
</form>
And the SQL to send the data on processor.php:
function sendData() {
//Connecting to sql db.
$connect = mysqli_connect("XXXXXX","XXXXXXXX","XXXXXXX","XXXXXXX");
//setting values from HTML form
$name = mysqli_real_escape_string($connect, $_POST['name']);
$age = mysqli_real_escape_string($connect, $_POST['age']);
$phone = mysqli_real_escape_string($connect, $_POST['phone']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
//Sending form data to sql db
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('$name', '$age', '$phone', '$email')");
}
sendData();
Just switch out the existing query with this one and it'll work. Cheers.
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('" . $name . "', '" . $age . "', '" . $phone . "', '" . $email . "')");
Try another insert type
mysqli_query($connect,"INSERT INTO users SET name='$name', age='$age',phone='$phone', email='$email')");
First of all try to insert into the db with static parameters. I mean something like this
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('name', 'age', 'phone', 'email')");
And check if your query works ! But you can otherwise try this one
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('" . $name . "', '" . $age . "', '" . $phone . "', '" . $email . "')");
I suggest you use Prepared Statements and if possible PDO
Good Luck
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
I'm very new to php and I really want to learn it. I'm learning from w3school, but I can't manage to do this (saving to database)... I also tried specifying the values in the .php and managed not to get error but it did not save in the database. Please tell me what is wrong in this.
<form action="submit.php" method="POST">
<p>Name:<input type="text" name="name"/></p>
<p>Email:<input type="text" name="email"/></p>
<p>Message:<textarea rows="3" cols="1" name="message"></textarea></p>
Submit
</form>
PHP File
<?php
$con = mysqli_connect("localhost","root","","kellywood");
if (mysqli_connect_errno()) {
echo "Failed to connect to Database";
} else {
echo "Connected";
}
$sql = "INSERT INTO kellywood (messages.name, messages.email, messages.message) VALUES ('$_POST[name]','$_POST[email]','$_POST[message]')");
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
No error, and I specified the values but it did not save in the database.
<?php
$con = mysqli_connect("localhost","root","","kellywood");
if (mysqli_connect_errno()) {
echo "Failed to connect to Database";
} else {
echo "Connected";
}
mysqli_query($con,"INSERT INTO kellywood(messages.name, messages.email, messages.message) VALUES ('Peter', 'Griffin',35)");
mysqli_close($con);
?>
Sorry for the noob question but i'm very new in php... Please help
There are a few things that are incorrect.
First:
Submit
which should be a button and not a link:
<input type="submit" name="submit" value="Submit">
And based on a comment that was made: "database is kellywood, messages is the table."
This:
mysqli_query($con,"INSERT INTO kellywood(messages.name, messages.email, messages.message)
VALUES ('Peter', 'Griffin',35)");
Should be:
mysqli_query($con,"INSERT INTO messages (name, email, message)
VALUES ('Peter', 'Griffin',35)");
However and based on your input variables, it should resemble more like this:
mysqli_query($con,"INSERT INTO messages (name, email, message)
VALUES ('" . $name . "', '" . $email . "', '" . $message . "')");
While assigning your input variables such as:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
Rewrite:
<?php
$con = mysqli_connect("localhost","root","","kellywood");
if (mysqli_connect_errno()) {
echo "Failed to connect to Database";
} else {
echo "Connected";
}
$name = $con->real_escape_string($_POST['name']);
$email = $con->real_escape_string($_POST['email']);
$message = $con->real_escape_string($_POST['message']);
mysqli_query($con,"INSERT INTO messages (name, email, message)
VALUES ('" . $name . "', '" . $email . "', '" . $message . "')");
mysqli_close($con);
?>
Or you can use:
<?php
$con = mysqli_connect("localhost","root","","kellywood");
if (mysqli_connect_errno()) {
echo "Failed to connect to Database";
} else {
echo "Connected";
}
$name = $con->real_escape_string($_POST['name']);
$email = $con->real_escape_string($_POST['email']);
$message = $con->real_escape_string($_POST['message']);
$sql = "INSERT INTO messages (name, email, message)
VALUES ('" . $name . "', '" . $email . "', '" . $message . "')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
else {
echo "SUCCESS!";
}
mysqli_close($con);
?>
HTML form
<form action="submit.php" method="POST">
<p>Name:<input type="text" name="name"/></p>
<p>Email:<input type="text" name="email"/></p>
<p>Message:<textarea rows="3" cols="20" name="message"></textarea></p>
<input type="submit" name="submit" value="Submit">
</form>
Both of the above worked on my server, using VARCHAR(255) for all 3 columns.
Columns: name - email - message
Try using a button type="submit", instead of the href tag.