I have this piece of code where i want to insert some values into a particular database. For some reason the records are not stored into the database. I have an idea that something is wrong with my mysql_query.
Possible problems which you think might cause this problem (I have checked , and they do not affect my problem):
Connection to the database is not established.
Variables do not contain values.
Here is the code:
<?php
include('includes/connect-db.php');
$firstname = mysql_real_escape_string(stripslashes(trim($_POST['firstname'])));
$surname = mysql_real_escape_string(stripslashes(trim($_POST['surname'])));
$username = mysql_real_escape_string(stripslashes(trim($_POST['username'])));
$password = mysql_real_escape_string(stripslashes(trim($_POST['password'])));
$email = mysql_real_escape_string(stripslashes(trim($_POST['email'])));
$tel = mysql_real_escape_string(stripslashes(trim($_POST['tel'])));
$month = mysql_real_escape_string(stripslashes(trim($_POST['month'])));
$day = mysql_real_escape_string(stripslashes(trim($_POST['day'])));
$year = mysql_real_escape_string(stripslashes(trim($_POST['year'])));
$address = mysql_real_escape_string(stripslashes(trim($_POST['address'])));
$postcode = mysql_real_escape_string(stripslashes(trim($_POST['postcode'])));
$city = mysql_real_escape_string(stripslashes(trim($_POST['city'])));
$country = mysql_real_escape_string(stripslashes(trim($_POST['country'])));
if(isset($_POST['submit_register'])) {
if(!empty($firstname) && !empty($surname) && !empty($username) && !empty($password) && !empty($email) && !empty($tel) && !empty($month) &&
!empty($day) && !empty($year) && !empty($address) && !empty($city) && !empty($country)) {
mysql_query("INSERT INTO customers (firstname, surname, username, password, email, tel, month, day, year, address, city, country)
VALUES ('$firstname','$surname','$username','$password', '$email', '$tel', '$month', '$day','$year','$address','$postcode','$city','$country')");
echo'success';
}
else{
echo'failure';
}
}
?>
First of all, you should not be using mysql_query since this extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, use the MySQLi or PDO_MySQL extension.
Regarding your code, you have forgotten to add the postcode column type in your SQL query.
mysql_query("INSERT INTO customers (firstname, surname, username, password, email, tel, month, day, year, address, postcode, city, country)
VALUES ('$firstname','$surname','$username','$password', '$email', '$tel', '$month', '$day','$year','$address','$postcode','$city','$country')");
If that does not work then check if any of the variables that you are trying to store to your database are missing and if they are then give them a null value.
For example:
if ( isset($_POST['firstname']) ) {
$firstname = mysql_real_escape_string(stripslashes(trim($_POST['firstname'])));
} else {
$firstname = '';
}
Alternatively you can use the "ternary operator":
$firstname = isset($_POST['firstname']) ? mysql_real_escape_string(stripslashes(trim($_POST['firstname']))) : '';
Do this for all your variables and then try to run the query.
What i usually do in such cases, i copy my sql query statement to mysql terminal.
I try the code there to find if it runs without any issue.
If it doesn't then mysql will raise an error.
if it does then i usually use sprintf function to format the query.
Something like this:
if(!empty($firstname) && !empty($surname) && !empty($username) && !empty($password) && !empty($email) && !empty($tel) && !empty($month) &&
!empty($day) && !empty($year) && !empty($address) && !empty($city) && !empty($country)) {
$query = sprintf('INSERT INTO customers (firstname, surname, username, password, email, tel, month, day, year, address, city, country) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',$firstname,$surname,$username,$password,$email,$tel,$month,$day,$year,$address,$postcode,$city,$country);
$result = mysql_query($query);
if($result){
echo 'Success';
}else{
echo 'Failure';
}
}
The %s is a string placeholder when using the sprintf function. there are several of them. check php docs.
Related
I have been struggling with this for a while now. Is there any way for me to get the "user_id" form my "users" table into my "orders" table when a customer places an order?
When using the second SQL statement, after the "INSERT INTO" statement, the system still says that the order has been successful. However, when I check my database the order has not even been inserted.
Without the use of the second SQL statement the order will be inserted correctly, with every field except the "user_id" being placed in the table.
I have also tried "INSERT INTO table2 (column1, column2, column3, ...) SELECT column1, column2, column3, ... FROM table1 WHERE condition;" Statement and that also does not work.
Would it work if only one SQL command was written? If so I am not sure how to do this.
Any help would be greatly appreciated.
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$type = mysqli_real_escape_string($conn, $_POST['type']);
$square_ft = mysqli_real_escape_string($conn, $_POST['square_ft']);
$materials = mysqli_real_escape_string($conn, $_POST['materials']);
$time= mysqli_real_escape_string($conn, $_POST['time']);
$date= mysqli_real_escape_string($conn, $_POST['date']);
$price= mysqli_real_escape_string($conn, $_POST['price']);
if (empty($price) || empty($time) || empty($date) || empty($type) || empty($square_ft) || empty($materials)) {
header("Location: ../placeorder.php?order=empty");
exit();
} else {
//Insert orders into database
$sql = "INSERT INTO orders (price, time, date, type, square_ft, materials,) VALUES('$price', '$time', '$date', '$type', '$square_ft','$materials');";
$sql = "INSERT INTO orders (user_id) FROM users;";
mysqli_query($conn, $sql);
header("Location: ../orderform.php?order=success");
exit();
}
}
?>
<?php
include_once 'footer.php';
?>
To get key from Users, you need to perform SELECT over users field, then to insert users key into orders. It would be something like this:
$sql1 = "SELECT user_id FROM users_table WHERE username='someusername'";
$userid = mysqli_fetch_assoc(mysqli_query($conn, $sql1));
$sql2 = "INSERT INTO orders (price, time, date, type, square_ft, materials, user_id) VALUES('$price', '$time', '$date', '$type', '$square_ft','$materials', '$userid');";
mysqli_query($conn, $sql1);
This may be the most simplest errors ever but I've written a registration script.. which I would say looks okay.. only issue is that it won't insert data... it still prints a message saying registration successful but no data actually goes into the database... see code below:
<?php
include("dbconfig.php");
if(isset($_POST['register'])){
if(empty($_POST['first-name']) or empty($_POST['last-name']) or empty($_POST['email-address']) or empty($_POST['reg-username']) or empty($_POST['reg-pass'])){
header("location:index-login-page.php?msg0=Please complete the required fields.");
}
else {
$fname = $_POST['first-name'];
$lname = $_POST['last-name'];
$email = $_POST['email-address'];
$username = $_POST['reg-username'];
$pass = $_POST['reg-pass'];
$checkusername = mysql_query("SELECT username FROM users WHERE username = '$username'");
$checkemail = mysql_query("SELECT email FROM users WHERE email = '$email'");
$resultusername = mysql_num_rows($checkusername);
$resultemail = mysql_num_rows($checkemail);
if( (($resultusername) ==1) or ($resultemail)==1){
header("location:index-login-page.php?msg1= Username or email address already exists.");
}
elseif( (($resultusername) == 0) && ($resultemail) ==0) {
$insertquery =("INSERT INTO users (firstname, lastname, email, username, password) VALUES ('$fname','$lname','$email','$username','$pass'");
header("location:index-login-page.php?msg1= Registration successful, please login.");
}
}
}
?>
Please do let me know what the error is (if there is one) because I can't seem to find it. Thanks.
Sohail.
$insertquery = ("INSERT INTO users (firstname, lastname, email, username, password) VALUES ('$fname','$lname','$email','$username','$pass'");
Should be:
$insertquery = mysql_query("INSERT INTO users (firstname, lastname, email, username, password) VALUES ('$fname','$lname','$email','$username','$pass'");
I have to warn you though: this is considered bad practice, you need to sanitize your database input
I'm trying to insert a date of birth into the database just one table but it's inserting 0000-00-00. I have a form that takes a date input or where <input type="date">. My insert command is:
if (($myname = $_GET['your_name']) && ($phone = $_GET['phone']) &&
($dob = date('Y-m-d', strtotime($_GET['dob'])))) {
$command = "INSERT INTO form_data (id, name, phone, dob)
VALUES ('', '".$db->real_escape_string($myname)."',
'".$db->real_escape_string($phone)."', '".$db->$dob."')";
My script works except the $dob. How do you handle an HTML5 input "date" input type into the database correctly? (I searched but didn't seem to work when I tried their suggestions here).
You assign date('Y-m-d', strtotime($_GET['dob']) to $dob, but later you try to reference it as $db->$dob. What you probably want it so to handle it just like the other variables and use $db->real_escape_string($dob):
$command = "INSERT INTO form_data (id, name, phone, dob)
VALUES ('', '".$db->real_escape_string($myname)."',
'".$db->real_escape_string($phone)."', '".$db->real_escape_string($dob)."')";
To make it more readable, I'd use sprintf though.
$command = sprintf("INSERT INTO form_data (id, name, phone, dob) VALUES ('', '%s', '%s', '%s')",
$db->real_escape_string($myname),
$db->real_escape_string($phone),
$db->real_escape_string($dob));
I suggest formatting your code so it's easier to read, and not doing assignments inside if blocks.
$myname = $_GET['your_name'];
$phone = $_GET['phone'];
$dob = strtotime( $_GET['dob'] );
if( !empty( $myname ) && !empty( $phone ) && $dob !== false ) {
$dob = date('Y-m-d', $dob );
$stmt = $dbConnection->prepare('INSERT INTO form_data ( id, name, phone, dob ) VALUES ( \'\', ?, ?, ? )');
$stmt->bind_param('s', $myname);
$stmt->bind_param('s', $phone);
$stmt->bind_param('s', $dob);
$stmt->execute();
$result = $stmt->get_result();
}
Note how I use mysqli instead of mysql_. It's safer.
By using $db->$dob in your VALUES set you're trying to access a member of $db called whatever value $dob is set to. You should be using $dob instead.
II created a form for inserting a new company and also on this page it is the PHP script which insert the data into the database.
I don`t know where it is the mistake in this code.
<?php
if (isset($_POST['submit']))
{
// Form has been submitted.
$query = mysql_query("INSERT INTO companies (name, subdomain0, subdomain1, subdomain2,
position, country, city, district, contact, set_up_date, address, phone, area_phone_code, website, fax, email)
VALUES ('{$_POST['name']}', '{$_POST['domain']}', '{$_POST['subdomain1']}',
'{$_POST['subdomain2']}', '{$_POST['position']}', '{$_POST['country']}', '{$_POST['city']}',
'{$_POST['district']}', '{$_POST['contact']}', '{$_POST['setdate']}', '{$_POST['address']}', '{$_POST['phone']}',
'{$_POST['areacode']}, '{$_POST['website']}', '{$_POST['fax']}', '{$_POST['email']}')");
$result = mysql_query($query, $connection);
if (!$result) {
echo "The company was not created.";
} else {
echo "The company was successfully created.";
}
}
?>
rewrite your code and remove those {} from the variables like that
VALUES ('$_POST['name']','$_POST['domain']', '$_POST['subdomain1']',...
1- be sure to escape them before you send them to database .
2-dont use mysql , use pdo or mysqli
to escape them do like that:
$name = mysql_real_escape_string($_POST['name']) ;
and then pass it to ur query like that
VALUES ('$name', .... <-- same with other columns
EDIT-
Try this
if (isset($_POST['submit'])) { // Form has been submitted.
$name = mysql_real_escape_string($_POST['name']) ;
$subdomain0 = mysql_real_escape_string($_POST['subdomain0']) ;
$subdomain1 = mysql_real_escape_string($_POST['subdomain1']) ;
$subdomain2 = mysql_real_escape_string($_POST['subdomain2']) ;
$position = mysql_real_escape_string($_POST['position']) ;
$country = mysql_real_escape_string($_POST['country']) ;
$city = mysql_real_escape_string($_POST['city']) ;
$district = mysql_real_escape_string($_POST['district']) ;
$contact = mysql_real_escape_string($_POST['contact']) ;
$set_up_date = mysql_real_escape_string($_POST['setdate']) ;
$address = mysql_real_escape_string($_POST['address']) ;
$phone = mysql_real_escape_string($_POST['phone']) ;
$areacode = mysql_real_escape_string($_POST['areacode']) ;
$website = mysql_real_escape_string($_POST['website']) ;
$fax = mysql_real_escape_string($_POST['fax']) ;
$email = mysql_real_escape_string($_POST['email']) ;
$query = mysql_query("INSERT INTO companies (name, subdomain0, subdomain1, subdomain2,
position, country, city, district, contact, set_up_date, address, phone, area_phone_code, website, fax, email)
VALUES ('$_POST['name']', '$subdomain0', '$subdomain1',
'$subdomain2', '$position', '$country', '$city',
'$district', '$contact', '$set_up_date', '$address', '$phone',
'$areacode, '$website', '$fax', '$email')");
echo "The company was successfully created.";
else {
echo "The company was not created.";
}
}
?>
you have to be careful with sql injections. you can go through the link to know of other options to mysql_* functions, as it is deprecated.
also its always better to try to find out the error by using mysql_error function to print out the error. (check the link for alternatives as this too is getting deprecated)
INSERT INTO companies
SET name = $name,
subdomain0 = $domain,
subdomain1 = $doamin1
so on
I am having a tough time figuring out how to write an if function in my code. I am trying to prevent my PHP form from allowing duplicates being submitted to my MySQL database. I am wanting to prevent a submission based on the email address being inputted into my form. Can someone guide me in the right direction? Thanks.
<?php
$dbc = mysqli_connect('n/a', 'n/a', 'n/a', 'n/a')
or die('Error connecting to MySQL server.');
$store_name = $_POST['storename'];
$full_name = $_POST['fullname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$fax = $_POST['fax'];
$email = $_POST['email'];
$url = $_POST['url'];
$query = "INSERT INTO store_location (store_name, full_name, address, city, state, zip, phone, fax, email, url) VALUES ('$store_name', '$full_name', '$address', '$city', '$state', '$zip', '$phone', '$fax', '$email', '$url')";
mysqli_query($dbc, $query)
or die('Error querying database.');
echo 'New TeachPro store added.';
echo '<br/><br/>';
mysqli_close($dbc);
?>
You should use a unique key on the email column on your database table. Now, if you try to insert the same email address twice, the MySQL responds with an according error message. You may catch those error message and present a useful error message text to the user.
I used that approach for checking usernames:
try
{
/** #var $userInsertUpdateStmt PDOStatement */
$userInsertUpdateStmt->execute();
}
catch(PDOException $e)
{
if($e->errorInfo[1] == 1062)
{
/* username already used */
return User::ERR_USERNAME_ASSIGNED;
}
return User::ERR_SQL;
}
SELECT count(*) FORM ... WHERE store_name = ... OR full_name=...
If you have 0 rows as a result of this query, you're good to go.
Also, your query is vulnerable to SQL-injection (google that).