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.
Related
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.
I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.
I'm running an insert query to insert user information into the database.
The fields to insert are username and email, and the email field is not mandatory.
The query run fine when the input includes the email, but when I entered nothing in the email, the PDO error always reports the error " Duplicate entry '' for key 'email' " .
$post = $this->input->post();
$sql = "INSERT INTO users (username, email) VALUES (:username, :email)";
$query = $this->db->conn_id->prepare($sql);
$query->bindValue (':username', $post['username'], PDO::PARAM_STR);
if ($email == false){
$query->bindValue(':email', '', PDO::PARAM_STR );
} else {
$query->bindValue(':email', $post['email'], PDO::PARAM_STR );
}
$query->execute();
First, as I mentioned in the comment, you need to set the email column to allow for null values. If you are not requiring an email address, then it is better to store a non-email as null rather than an empty string - but in this case it is necessary because the column is unique.
Then, try this code:
$post = $this->input->post();
if (!$post['email']){
$post['email'] = NULL;
}
$sql = "INSERT INTO users (username, email) VALUES (:username, :email)";
$query = $this->db->conn_id->prepare($sql);
$query->execute(array($post['username'], $post['email']));
My sql query is :
"INSERT INTO
order customer_id = $customer_id
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
I get the error
Notice: 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 'order customer_id =1,firstname ='kuldeep',lastname
='pathak',email ='kuldeep.pat' at line 1 Error No: 1064
You didnt understand how to write SQLs as it seems.
$sql = 'INSERT INTO `order` (customer_id, firstname, blablabla) VALUES ('.$custormer_id.','.$firstname.','.$blablabla.')';
Please look at some basic tutorials about SQL.
"INSERT INTO
`order` SET customer_id = " . $customer_id . "
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
Should be alright. DonĀ“t forget to escape your data though.
Try
"INSERT INTO `Order` (customer_id, firstname, lastname, email, telephone, fax, ip, date_added, date_modified)
VALUES ($customer_id, '$firstname', '$lastname', '$email', '$telephone', '$fax', '$ip', NOW(), NOW())"
The right syntax is : INSERT INTO tablename (columns) VALUES (values);
If you're likely to have user submitted fields in the dataset or appostrophes or anything else that could cause problems for any reason you'd want something more like
$query = sprintf("INSERT INTO `table` (`Name`, `Email`, `AnotherField`) VALUES ('%s', '%s', '%s'",
mysql_real_escape_string( $_POST['Name'] ),
mysql_real_escape_string( $_POST['Email'] ),
mysql_real_escape_string( $_POST['AnotherField'] )
);
This will sanitise your inputs as well
Use prepared statement to avoiding sql injection.
$custormer_id = "2000";
$firstname = "first name";
$etc = "some other values";
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare("INSERT INTO order(customer_id, firstname, etc) VALUES (?, ?, ?)");
$stmt->bind_param('iss', $custormer_id, $firstname, $etc);
// first parameter is corresponding variable type of inserting values,eg i=interger, s=string
$stmt->execute();
$stmt->close();
http://php.net/manual/en/mysqli-stmt.bind-param.php
So I am trying to create a form that puts data in a table, and I got it to work, but when it goes to the table, it just creates empty rows. Here is my code, please help me out.
form.php
<form action="tableinsert.php" method="post">
First Name:<input type="text" name="fname"> <br/>
Last Name:<input type="text" name="lname"><br/>
Username:<input type="text" name="uname"><br/>
Password:<input type="text" name="password"><br/>
Email:<input type="text" name="email"><br/>
</form>
tableinsert.php
<?php
$sc = mysqli_connect ("localhost" , "dbname" , "password");
if (mysqli_errno($sc))
{
echo "Sorry, I couldn't connect to the database. If you keep getting this error, please email the webmaster at natashaharrell#hotmail.com " . mysql_error;
}
$si = "INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ('$_POST[fname]' , '$_POST[lname]' , '$_POST[uname]' , '$_POST[password]' , '$_POST[email]' )";
if (!mysqli_query($sc, $si))
{
echo "Sorry there seems to be a problem: " . mysqli_errno($sc) ;
}
else
{
echo "1 record added.";
}
mysqli_close($sc);
?>
Try that
$si = "INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ('".$_POST["fname"]."' , '".$_POST["lname"]."' , '".$_POST["uname"]."' , '".$_POST["password"]."' , '".$_POST["email"]."' )";
you might be getting empty row because the form is getting filled with empty values and gets submitted automatically each time you load the page. you should use submit button.
Use mysqli prepare() http://php.net/manual/en/mysqli.prepare.php to insert data into your SQL queries.
There are a lot of simple mistakes that novices can make, to render their code vunerable to security issues, thats why mysql_* has been depreciated
<?php
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO sdb_users (fname, lname, uname, password, email) VALUES ( ?, ?, ?, ?, ? )")) {
/* bind parameters for markers */
$stmt->bind_param("s", $_POST["fname"]);
$stmt->bind_param("s", $_POST["lname"]);
$stmt->bind_param("s", $_POST["uname"]);
$stmt->bind_param("s", $_POST["password"]);
$stmt->bind_param("s", $_POST["email"];
/* execute query */
$stmt->execute();
?>
Replace this
$si = "INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ('$_POST[fname]' , '$_POST[lname]' , '$_POST[uname]' , '$_POST[password]' , '$_POST[email]')";
With this:
$si = 'INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ("' . $_POST['fname'] . '", "' . $_POST['lname'] . '" , "' . $_POST['uname'] . '", "' . $_POST['password'] . '", "' . $_POST['email'] . '")';
That fixes your actual problem, but as an aside, wrap each of those POST values in MySQLi's string escaping function (I'm a PDO user, but I believe it's MySQLi::real_escape_string). That helps protect you from SQL injection.
The reason it wasn't working is you didn't put the array key in quotes. I changed from double quotes to single, because it's easier to escape values and saves PHP having to process the magic-quoted string.
Firstly, it is a a convention to store the values obtained from the form fields into variables. Do that. Then after that you must clean up the values you got from the text fields. Basically you must clear it of all unexpected stuff like SQL injections (complex stuff). To do that you must use MySQL real escape string. After that is done, substitute the variables in the place of your earlier variables such as $_POST['fname'] or $_POST['lname'].
Hopefully after this you will have a script that works fully.
The values you are using in the query are not correct. Try it this way.
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$uname = $_POST['uname'];
$pwd = $_POST['password'];
$email = $_POST['email']
$si = "INSERT INTO sdb_users (fname, lname, uname, password, email)
VALUES ('$fname' , '$lname' , '$uname' , '$pwd' , '$email' )";
EDIT:
Use mysql_real_escape_string() function to sanatize the data before inserting.