I'm a beginner at this. Basically I have a form that has the correct names set up, and it sends the data to the MySQL table correctly, but it always inserts an additional 4 blank rows/ID's whenever I execute the form.
Here's the result every time: http://i.stack.imgur.com/bnx5D.png
I'm not sure whether if there's something wrong with the code or the setup itself, can anybody help?
PHP code:
<?php
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$member_company = $_POST['member_company'];
$member_address1 = $_POST['member_address1'];
$member_address2 = $_POST['member_address2'];
$member_city = $_POST['member_city'];
$member_country = $_POST['member_country'];
$member_post_code = $_POST['member_post_code'];
$member_phone = $_POST['member_phone'];
mysql_connect ("localhost", "username", "password") or die ('Error: ' . mysql_error());
mysql_select_db ("database");
$query="INSERT INTO Orders (ID, email, first_name, last_name, member_company, member_address1, member_address2, member_city, member_country, member_post_code, member_phone)
VALUES ('NULL', '".$email."', '".$first_name."', '".$last_name."', '".$member_company."', '".$member_address1."', '".$member_address2."', '".$member_city."', '".$member_country."', '".$member_post_code."', '".$member_phone."')";
mysql_query($query) or die ('Error updating database');
?>
The thing is that every time you do a request you save the data on the table.
You should check if it is a POST request
if(isset($_POST){
//Then the form has been submitted
}
This is running on every GET request also, that's why you get those empty records.
Related
I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);
I cannot find any syntax errors for the life of me so I don't understand why the data is not being inserted into my database. When I run the script in my browser with text instead of variables and no if statement I get a successful connection but It doesn't insert the data into mysql. Its driving me nuts! Thanks in advance.
PHP:
<?php
// Establish secure connection
$link = mysql_connect('myserver', 'myuser', 'mypass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db(events_60);
if ($_POST['requester'] == "NewSale") {
$FirstName = $_POST['First_Name'];
$LastName = $_POST['Last_Name'];
$Birthday = $_POST['UserBirthday'];
$PhoneNumber = $_POST['PhoneNo'];
$Email = $_POST['UserEmail'];
mysql_query($link, "INSERT INTO events_60 (LastName, FirstName, Birthday, Phone, email)
VALUES('$LastName', '$FirstName',' $Birthday', '$PhoneNumber', '$Email')")
or die ("SYSTEM FAILURE");
echo 'System Updated';
} // close first if for post
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// close mysql connection
mysql_close();
?>
Assuming all data is posting correctly to the webpage I think the error resides here:
mysql_select_db(events_60);
It should be:
mysql_select_db('events_60', $link);
http://www.php.net/manual/en/function.mysql-select-db.php
First of all select_db query should be
mysql_select_db('events_60',$link);
Then second problem is in mysql_query. It should be like this:
mysql_query("INSERT INTO events_60 (LastName, FirstName, Birthday, Phone, email)
VALUES('$LastName', '$FirstName',' $Birthday', '$PhoneNumber', '$Email')",$link)
or die ("SYSTEM FAILURE");
$link identifier should come after query.
Hope that fixes it. :)
Thank you guys, worked it out, turns out it was in the js a word wasn't spelled correctly, always something simple
This is my script to write data to my database on my local server, it currently only writes to 2 fields, not the alias one, have I done anything wrong? I've triple checked the names in both the html form and the database field.
<?php
// 1. Create connection to database
mysql_connect('localhost','root','') or die('Could not connect to mysql: <hr>'.mysql_error());
// 2. Select database
mysql_select_db("trialdb") or die('Could not connect to database:<hr>'.mysql_error());
// 3. Assign variables (after connection as required by escape string)
$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];
// 4. Insert data into table
mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')");
Echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close()
?>
First of all you should always check if the POST variables are being sent correctly:
if (
!isset($_POST['alias']) or
!isset($_POST['name']) or
!isset($_POST['email'])
) // something is wrong
Second, you don't want to inject user input directly into the sql query. You should perform some escaping first (or even better replace the mysql_* deprecated drivers with PDO or mysqli and just use prepared statements):
$alias = mysql_real_escape_string($_POST['alias']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
Third, you may want to check if the query performed correctly before printing a success message:
$res = mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')");
echo ($res)
? 'Your information has been successfully added to the database.'
: 'Your information couldn't be added to the database';
you can try
<?php
$conn = mysql_connect('localhost','root','') or die('Could not connect to mysql: '.mysql_error());
mysql_select_db("trialdb", $conn) or die('Could not connect to database:'.mysql_error());
$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];
mysql_query("INSERT INTO user_data (`alias`, `name`, `email`) VALUES ('$alias', '$name', '$email')", $conn);
echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close();
?>
I'm currently trying to make a page via php which allows the user to update data in my database. I'm experiencing two problems: first when I run my code I get the "Error: Query was empty", however updates were made to the database and this leads me to my second problem. Fields that were left empty (a user doesn't have to enter data into all the fields if they only have one or two things to update) become blank after the updates are made. This is because my current script updates all elements, but is there any way I can have it where if the user leaves an input field blank, nothing gets changed when the database is updated?
Here is my code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
To answer your question, you need to catch the query's result and check for errors on that.
$query = mysql_query(/*query*/);
if (!$query)
//error handling
Be sure to read up on SQL injections, as per my comment.
To better help you understand the behavior you were seeing, I will explain to you what was wrong with your code:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
That first part was executing a MySQL query, regardless of that fact that you did not assign it's return value to a variable.
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
The second part was attempting to run a query by passing the first parameter $sql which has not been set, and the second parameter $con which also appears to not have been set. The first query you ran executed just fine while the second one could never execute. Your solution:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
if (!mysql_query($sql,$con)) Here $sql and $con are not defined. Should you be running mysql_query twice?
Few guesses:
There is no mysql connect function I assume it's called elsewhere
Print out your query string. I've always found explicitly denoting what is a string and what is a variable by 'SELECT * FROM '.%tblvar.';'; to be much more debug friendly.
So here is the deal. I have looked around everywhere, and all other techniques relate to refreshing the browser, and methods to prevent the php page from resubmitting the post data. I am new to this (obviously :p) But anyways, my questions I believe is simple. I just want a method, possibly an if else statement that would check the post data entries, and if there is a match already in my table, than do not execute the query. I am not worried about querying all of the results of the table, as I only suspect this table will ever have 50-60 entries.
Here is the php page that handles the form submission:
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$submitDate = date("Y-m-d");
mysql_connect ("localhost", "abc", "123") or die ('Error: ' . mysql_error());
mysql_select_db ("members");
$query = "INSERT INTO persons (ID, firstName, lastName, email, city, state, submitDate)VALUES (
'NULL',
'".$firstName."',
'".$lastName."',
'".$email."',
'".$city."',
'".$state."',
'".$submitDate."'
)";
mysql_query($query) or die ('Error Updating database');
echo "Database Updated With: " .$firstName ." " .$lastName ." " .$email ." " .$city ." " .$state;
mysql_close($con);
Sorry, cant ever seem to get my php to format correctly with those code braces. Anyways. just to re-iterate, looking for a way to maybe based on the first and last name. if those already exist, then do not allow the submission of the data. I have tried a few if then statements but i do not think I am getting the concept down of comparing the result to my query. I hope this all makes sense!!!
I would suggest adding a UNIQUE index on the columns you want to have unique.
You can just use INSERT IGNORE INTO ... and let MySQL handle it.
$query = "INSERT IGNORE INTO persons (ID, firstName, lastName, email, city, state, submitDate) VALUES (
'NULL',
'".$firstName."',
'".$lastName."',
'".$email."',
'".$city."',
'".$state."',
'".$submitDate."'
)";
Is your problem only that refreshing the page resends the POST data? The pretty much standard way to prevent that is to redirect the browser after having processed the form data, like so:
header('Location: ' . $_SERVER['PHP_SELF']);
Keep in mind, changing headers has to be done before any output is sent to the browser, so this should be above your doctype, and be sure there is no white space before either.
One way of doing this is to make sure your table has appropriate primary keys set (firstname and lastname at least), and then just trying the insert and seeing whether it fails on duplicate. You can check the error message using the mysql_error() function for this purpose.
You can do a select on the database with those two fields to check if a row already exists, but if this is something that needs to be unique there should also be a unique index on those two columns in your MySQL table.
I had this issue as well. Basically what I did is before the insert, do a select on the criteria that would qualify as a duplicate and check for it to return; if it does not we are ok to enter.
$query = "SELECT COUNT(id) AS mycount FROM persons WHERE firstName = '".$firstnName."' AND lastName = '".$lastName."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if($row['mycount'] == 0) {
//Do insert
}