Trying to write to a MySQL database with a PHP form - php

I'm trying to do a simple write to database with an HTML form, using PHP.
I've run the SQL query in the database and it works perfectly. However, using the form doesn't work. I'm not sure why. Any help? The user/pass/db name are all correct.
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
//also email it to us besides writing it into the database
mysql_close($con);
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/>
<br/>
<strong>Last name:</strong> <input type="text" name="lastName"/>
<br/>
<strong>Email:</strong> <input type="text" name="email"/> #####Put a javascript checker for valid emails, like name#site.com format
<br/>
<br/>
<strong>Idea:</strong>
<br/>
<textarea rows="10" cols="30" name="idea">
Hit us with your best shot.
</textarea>
<br/>
<input name="submit" type="submit" value="Submit"/>
</form>

You forgot the "action = nameofyourpage.php" inside the form markup. And I would add a "or die (mysql_error())" at the end of your query to check the syntax of the request.

you've got a few errors in your script - please check the following
http://pastie.org/1056569
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
$sqlCmd = sprintf("INSERT INTO data (firstName, lastName, email, idea)
VALUES ('%s','%s','%s','%s')",
mysql_real_escape_string($_POST["firstName"]),
mysql_real_escape_string($_POST["lastName"]),
mysql_real_escape_string($_POST["email"]),
mysql_real_escape_string($_POST["idea"]));
mysql_query($sqlCmd);
mysql_close($con);
}
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/><br/>
<strong>Last name:</strong> <input type="text" name="lastName"/><br/>
<strong>Email:</strong> <input type="text" name="email"/>
<strong>Idea:</strong><br/>
<textarea rows="10" cols="30" name="idea">Hit us with your best shot.</textarea><br/>
<input name="submit" type="submit" value="Submit"/>
</form>

You already have the answer to your question as to why it was not working, but please check this article about SQL injection attacks before putting this code into production.

you have error
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES
('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
Error = '$_POST['firstName']' you have chatter ' in post field
and you can change
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$email = $_POST['email'];
$idea = $_POST['idea'];
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('{$firstname}','{$lastname}', '{$email}', '{$idea}')");
or with mysql query
mysql_query("INSERT INTO data SET firstName='{$firstname}', lastName='{$lastname}',
email='{$email}', idea='{$idea}'");

Related

PHP - INSERT Query failing, returns no error. Beginner

<form action="" method="post">
<input type="text" id="title" name="title" />
<input type="text" id="link" name="link" />
<input type="submit" value="Add resource" />
<?php
if(isset($_POST['title']) && $_POST['link']) {
$t = $_POST['title'];
$l = $_POST['link'];
$con = mysqli_connect("localhost","root","","rman");
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL:" . mysqli_connect_error());
}
mysqli_query($con, "INSERT INTO tutorials (id, title, link, section) VALUES ('','$t','$l','')");
}
?>
</form>
How can this not work? I have removed every single part that might have caused this. Nothing is going in the database, no errors returning whatsoever.
For everyone wondering:
DB name: rman
Table name: tutorials
colums: id (INT11, Auto increment), title (Text), link (Text), section(INT11)
Am I being blind here? I'm sorry if thats the situation. Hope someone can see what I am doing wrong and help me out.
This should work.
<?php
if(isset($_POST['title']) && $_POST['link']) {
$t = $_POST['title'];
$l = $_POST['link'];
$con = mysqli_connect("localhost","root","","rman");
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL:" . mysqli_connect_error());
}
mysqli_query($con, "INSERT INTO tutorials (id, title, link, section) VALUES ('', '$t', '$l', '1')");
}
?>
<form action="" method="post">
<input type="text" id="title" name="title" />
<input type="text" id="link" name="link" />
<input type="submit" name="submit" value="Add resource" />
</form>
use mysqli_error() to check error code, as well as don't insert blank id if it's AI
Thusly:
if (!mysqli_query($con, "INSERT INTO tutorials (id, title, link, section) VALUES ('','$t','$l','')"))
{
echo mysqli_error($con);
}

php won't insert into mysql. no errors

I create php and mysql database and table. This is my code:
<form action="proba.php" method="post" />
<p> ime: <input type="text" name="ime" /></p>
<p> prezime: <input type="text" name="prezime" /></p>
<p> datum rodjenja: <input type="text" name="godiste" /></p>
<p> jmbg: <input type="text" name="jmbg" /></p>
<p> adresa: <input type="text" name="adresa" /></p>
<p> email: <input type="text" name="email" /></p>
<p> telefon: <input type="text" name="telefon" /></p>
<p> datum: <input type="text" name="datum" /></p>
<input type="submit" value="insert" />
</form>
and here is my code to connect with mysql
<?php
$link = mysqli_connect("127.0.0.1", "root", "1511", "test");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
$db_selected = mysql_select_db ('test', $link);
if (!$db_selected) {
die('nedostupno ' . test . ' : ' . mysql_error ());
}
$values = $_POST['ime'];
$values2 = $_POST['prezime'];
$values3 = $_POST['godiste'];
$values4 = $_POST['jmbg'];
$values5 = $_POST['adresa'];
$values6 = $_POST['email'];
$values7 = $_POST['telefon'];
$values8 = $_POST['datum'];
$sql = "INSERT INTO users (ime, prezime, godiste, jmbg, adresa, emal, telefon, datum) VALUES ('values', 'values2', 'values3', 'values4', 'values5', 'values6', 'values7', 'values8')";
}
echo 'Connected successfully';
?>
And this is mysql:
You have made some few mistakes so that the query might not be inserting datas into the phpmyadmin database. The basic error you have made is in the insert query by not concatenating the values that you want in the VALUES section and the insert statement syntax will be like this.
Insert Syntax:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.
So the basic form will be the same as you display in the question. I have added a name alone to the submit button and re-modified it.
HTML FORM:
<form action="proba.php" method="post" />
<p> ime: <input type="text" name="ime" /></p>
<p> prezime: <input type="text" name="prezime" /></p>
<p> datum rodjenja: <input type="text" name="godiste" /></p>
<p> jmbg: <input type="text" name="jmbg" /></p>
<p> adresa: <input type="text" name="adresa" /></p>
<p> email: <input type="text" name="email" /></p>
<p> telefon: <input type="text" name="telefon" /></p>
<p> datum: <input type="text" name="datum" /></p>
<input type="submit" name="save" value="insert" />
</form>
And your proba.php will look like this as i have coded below.
<?php
//Database connection Part of Mysqli
$host="localhost";
$user="root";
$password="1511";
$db="test";
$conn=new mysqli($host,$user,$pass,$db);
// Print Error if the connection is failed.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Print Error if the DB is not selected.
if (!mysqli_select_db($conn, $db)) {
die("Uh oh, couldn't select database --> $db" . $conn->connect_error . ' >');
}
if(isset($_POST['save']))
{
$values = $_POST['ime'];
$values2 = $_POST['prezime'];
$values3 = $_POST['godiste'];
$values4 = $_POST['jmbg'];
$values5 = $_POST['adresa'];
$values6 = $_POST['email'];
$values7 = $_POST['telefon'];
$values8 = $_POST['datum'];
$sql = "INSERT INTO users (`ime`, `prezime`, `godiste`, `jmbg`, `adresa`, `emal`, `telefon`, `datum`) VALUES ('".$values."', '".$values2."', '".$values3."', '".$values4."', '".$values5."', '".$values6."', '".$values7."', '".$values8."')";
$query = mysqli_query($conn,$sql);
echo 'Inserted successfully';
}
?>
Note: You first put echo to the Insert Statement and then break the execution by putting the exit; and you copy the statement that is echoed and place it in SQL of the DB and then check whether any error occurs in insertion. If no error occurs remove the echo and delete the exit;
And you are inserting the data successfully. Hope so i would have given a clear explanation about the data not inserting into the database.
Do something like this:
$values = $_POST['ime'];
$values2 = $_POST['prezime'];
$values3 = $_POST['godiste'];
$values4 = $_POST['jmbg'];
$values5 = $_POST['adresa'];
$values6 = $_POST['email'];
$values7 = $_POST['telefon'];
$values8 = $_POST['datum'];
$sql = "INSERT INTO users (ime, prezime, godiste, jmbg, adresa, emal, telefon, datum) VALUES ('".$values."', '".$values2."', '".$values3."', '".$values4."', '".$values5."', '".$values6."', '".$values7."', '".$values8."')";
mysqli_query($link,$sql);
From the very first mistake.
You have added your success code in if condition where Server
connection object is gets fail to connect.
When you are using mysqli_connect for server connection then why
you are using mysql_connect.
Missing of query execution line. i.e. mysqli_query($link, $sql).

Inserting data to database via web form

I have looked for the answer to my question and seeing as all programming varies I can't seem to fix my problem. I have created a php file that does in fact connect to my database. However, when I try submitting data to my database via my php webpage it won't go through. The same happens when I try to display info from my database to a webpage. Seeing as it is in fact connecting to the database, I'm not sure what the issue is. Any help is appreciated, try to dumb it down for me as much as possible when you answer. Also, I have triple-checked my database name and table names to make sure they match up with my coding. Here's my code:
Connection to database:
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'art database');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
My form to insert data to my database:
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert = "INSERT INTO users (first name, last name) VALUES ('$fname','$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
$newrecord = "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
The reason it's not working is because you have spaces in your columns/query.
INSERT INTO users (first name, last name)
wrap them in backticks like this:
INSERT INTO users (`first name`, `last name`)
It is not recommended to use spaces in column names or tables.
Try and use underscores instead, or remove the spaces and make the appropriate changes to your columns in your DB also, if you do.
You should also consider using:
('" . $fname . "','" . $lname . "')
instead of ('$fname','$lname')
I'm also questioning this => DEFINE ('DB_NAME', 'art database');
There is a space in between art and database. If that is the case and is in fact the name you've given your DB, do rename it to art_database and use DEFINE ('DB_NAME', 'art_database'); instead.
And do use the following for added protection:
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
Interesting article to read on protection:
How can I prevent SQL injection in PHP?
EDIT: (options)
OPTION 1, in 2 files:
First, rename your columns to firstname and lastname and use the following code and naming your file insert-data.php
DB query file (insert-data.php)
<?php
if (isset($_POST['submit'])) {
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Then in a seperate file, your HTML form; name it db_form.php for example:
HTML form (db_form.php)
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
</body>
</html>
NEW EDIT - OPTION 2, all in one file:
Use this in one page, with nothing else added:
<?php
if (isset($_POST['submit'])) {
if(empty($_POST['fname'])) {
die("Fill in the first name field.");
}
if(empty($_POST['lname'])) {
die("Fill in the last name field.");
}
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="">
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
I have made some changes, which is working fine for me
Where i can ignore if data is already in database
You Can try this to
<?php
if (isset($_POST['submit'])) {
include('db.inc.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
// $sqlinsert = "INSERT INTO `user` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
$sqlinsert = "INSERT IGNORE INTO `dbname`.`user` (`fname`, `lname`) VALUES ( '$fname', '$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Where db.inc.php is a different file in same directory for connecting database
<?php
$dbcon=mysqli_connect("localhost","dbuser","yourpassword","dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Stop form from submitting on page load

How do I stop the form from submitting on page load or refresh? I'm not worried about parameterizing right now. Thanks in advance!
$firstname = $_POST['firstname']
$lastname = $_POST['lastname']
$sql = ("INSERT INTO table (firstname, lastname) VALUES ('$_POST[firstname]' , ' $_POST[lastname]')");
mysql_query($sql) or die ("Error is: ".mysql_error());
<form name="add-name" id="add-name" method="post" action="/add-name.php">
<button type="submit">Save</button>
<fieldset>
<label>First Name *</label>
<input name="firstname" type="text" id="firstname" />
</fieldset>
<fieldset>
<label>Last Name *</label>
<input name="lastname" type="text" id="lastname" />
</fieldset>
</form>
if (isset($_POST['firstname'])) {
$firstname = $_POST['firstname']
$lastname = $_POST['lastname']
$sql = ("INSERT INTO table (firstname, lastname) VALUES ('$_POST[firstname]' , ' $_POST[lastname]')");
mysql_query($sql) or die ("Error is: ".mysql_error());
}
If you're only trying to stop the query from being executed, then bob's code will work.
If you're also trying to stop the "Would you like to re-submit the form" dialog box, then you'll also want to use headers to redirect back to the page after executing the query.
header("Location: /add-name.php"); // assuming add-name.php is the name of your file

Beginner trouble with PHP & MySQL

I am very new to PHP & MySQL. Just designing websites for friends as a hobby, so any help is greatly appreciated. When I have a simple contact form on my page I keep getting error messages when submitting the information. Here is the PHP:
<?php
$con = mysql_connect("localhost","user","password");
if (!$con)) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database_name", $con);
$sql="INSERT INTO contact (first_name, last_name, email, phone, message)
VALUES
('$_POST[first_name]','$_POST[last_name]','$_POST[email]','$_POST[phone]','$_POST[message])";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
I put in my username & password where necessary, but I keep "localhost" there. Is this correct? I have hosting through webhostingpad. I also insert my database name above. Here is my HTML:
<!--Start of order form-->
<form id="contactform" method="POST" action="http://www.talephotography.com/insert.php">
<p><label>First Name:<br />
<input type="text" name="first_name" class="textfield" value="" />
</label></p>
<p><label>Last Name:<br />
<input type="text" name="last_name" class="textfield" value="" />
</label></p>
<p><label>Email: <br />
<input type="text" name="email" class="textfield" value="" />
</label></p>
<p><label>Phone: <br />
<input type="text" name="phone" class="textfield" value="" />
</label></p>
<p><label>Message: <br />
<textarea name="message" class="textarea" cols="45" rows="5"></textarea>
</label></p>
<p><input type="submit" name="submit" class="button" value="Submit" /></p>
</form>
<!--End of order form-->
I can elaborate anywhere necessary.
Changed some of the code, it's only posting the email address to the database however.
mysql_select_db("databasename", $con);
$first = mysql_real_escape_string($_POST['first']);
$last = mysql_real_escape_string($_POST['last']);
$email = strip_tags(mysql_real_escape_string($_POST['email']));
$number = preg_replace('/[^0-9]/', '', $_POST['number']);
$number = (int) $number;
$sql="INSERT INTO contact (first, last, email, phone);
VALUES
('$first','$last','$email','$number')";
There's my code, however when I check my database the only info listed is the email address.
localhost is correct if the database server is on the same machine as the web server. When you set up the database it should have told you somewhere what you need to connect to.
That aside, escape your -----------ing inputs!!!!
Seriously, take those variables and wash them thoroughly with mysql_real_escape_string and then concatenate them into the query. You'll thank me later.
You have an extra ) in your if statement:
if (!$con)) {
should be
if (!$con) {
if (!$con)) it is wrong one extra ')' present here, remove ')' and then execute
for example
if (!$con){
//do something
}
Its query that is wrong, you have a ; that is in the middle of your query.
$sql="INSERT INTO contact (first, last, email, phone);
VALUES
('$first','$last','$email','$number')";
Notice it on the end of first line. Change this to:
$sql="INSERT INTO contact VALUES
('$first','$last','$email','$number')";
The problem is with your third line
$con = mysql_connect("localhost","user","password");
if (!$con)) {
die('Could not connect: ' . mysql_error());
}
there is an extra closing bracket ) in your third line. Remove it and then voilĂ !
hope this helps.

Categories