Why does my php form keep yielding empty rows in mysql? - 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.

Related

php error Column count doesn't match value count at row 1? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I have checked for similar questions regarding the error however they didn't match the issue I seem to be having.
Getting the following error when attempting to insert data into database:
Column count doesn't match value count at row 1?
Here is a screenshot of the database table:
In the HTML a form, with an action of the php file, has multiple inputs with the names: name, surname, DateOfBirth, email, password, confirm-password
PHP:
<?php
// Only process the form if $_POST isn't empty
if ( ! empty( $_POST ) ) {
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', '', 'pptpp' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = "INSERT INTO user ( Forename, Surname, DateOfBirth, Email, Password ) VALUES ( '{$mysqli->real_escape_string($_POST['name, surname, DateOfBirth, email, password '])}' )";
$insert = $mysqli->query($sql);
// Print response from MySQL
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_id}";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
// Close our connection
$mysqli->close();
}
?>
The following part
$mysqli->real_escape_string($_POST['name, surname, DateOfBirth, email, password ']
is invalid for two reasons:
mysqli::real_escape_string() takes only 1 argument at a time, a string (unless using procedural, mysqli_real_escape_string(), then the first is the connection, then the string as the second)
The $_POST can't be accessed in that way, I highly doubt you have one field named all that. You'll have to specify the index, as $_POST['name'] etc.
The solution is to match each column with the respective escaped value from $_POST,
like $mysqli->real_escape_string($_POST['name']) for the name,
$mysqli->real_escape_string($_POST['email']) for the email and so on, an example could be assigning it to variables, and using those in the query, as shown below.
$name = $mysqli->real_escape_string($_POST['name']);
$surname = $mysqli->real_escape_string($_POST['surname']);
$dob = $mysqli->real_escape_string($_POST['DateOfBirth']);
$email = $mysqli->real_escape_string($_POST['email']);
$password = $mysqli->real_escape_string($_POST['password']);
$sql = "INSERT INTO user (Forename, Surname, DateOfBirth, Email, Password) VALUES ('$name', '$surname', '$dob', '$email', '$password')";
$insert = $mysqli->query($sql);
Then you should note that even with mysqli::real_escape_string(), it's not secure against SQL injection, and that you should use parameterized queries. An example of that is given below.
// Insert our data
$sql = "INSERT INTO user (Forename, Surname, DateOfBirth, Email, Password) VALUES (?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("sssss", $_POST['name'], $_POST['surname'], $_POST['DateOfBirth'], $_POST['email'], $_POST['password']);
if (!$stmt->execute())
die("Execution failed: ".$stmt->error);
echo "Success! Row ID: ".$stmt->insert_id;
$stmt->close();
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
Usage of PHP error-reporting would've likely mentioned something about undefined indexes when you use the current escape. Always (in development) let PHP give you the errors, by enabling error-reporting with error_reporting(E_ALL); ini_set("display_errors", 1); at the top of your file.
Also note that storing passwords in plain-text is a big no. You should use functions like password_hash() / password_verify() to properly and securely store your users passwords.
References
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/mysqli-stmt.prepare.php
How can I prevent SQL injection in PHP?

Unable to locate sql error in php

Error message i've been recieving
Parse error: syntax error, unexpected 'INTO' (T_STRING) in D:\ServerFolders\Web\tokens\insert.php on line 17
Line 17
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
Full code
<?php
//Connect to DB
$con=mysql_connect(localhost,root, "",APROJECT) or die (mysql_error());
// Check connection
if (mysql_connect_errno()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
// escape variables for security
$Forename = mysql_real_escape_string($con, $_POST['Forename']);
$Surname = mysql_real_escape_string($con, $_POST['Surname']);
$Email = mysql_real_escape_string($con, $_POST['Email']);
$Username = mysql_real_escape_string($con, $_POST['Username']);
$Password = mysql_real_escape_string($con, $_POST['Password']);
$DOB = mysql_real_escape_string($con, $_POST['DOB']);
//SQL query to add data to DB
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB);
if (!mysql_query($con,$sql)) {
die('Error: ' . mysql_error($con));
}
echo "1 record added";
mysql_close($con);
?>
First of all, mysql_* is not supported anymore and advised to use PDO or mysqli_* instead.
You should put query into quotes;
$sql= "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
It may not work! Because you have to put values into single quotes. So better approach is using parameterized query.
For this time only I suggest using sprintf() function.
$sql= sprintf("INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')", $Forename, $Surname, $Email, $Username, $Password, $DOB);
Try adding quotes
$sql= "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB);
The above line needs to be a string and in one line (variables in strings which start and end in " can be directly written into it):
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
If you want it to be in multiple lines for better readability, you can use the nowdoc syntax with variables embeded in {}:
$sql <<<'EOD'
INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ({$Forename}, {$Surname}, {$Email}, {$Username}, {$Password}, {$DOB})
EOD;
Last approach would be to concat the string with .:
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) " .
"VALUES (" . $Forename . ", " . $Surname . ", " . $Email . ", " . $Username . ", " . $Password . ", " . $DOB . ")";
See this reference: http://php.net/manual/de/language.types.string.php
On a side note, don't forget to escape your variables in your mysql query with mysql_real_escape_string to prevent SQL Injection!
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) " .
"VALUES (" . mysql_real_escape_string($Forename) . ", " . mysql_real_escape_string($Surname) . ", " . mysql_real_escape_string($Email) . ", " . mysql_real_escape_string($Username) . ", " . mysql_real_escape_string($Password) . ", " . mysql_real_escape_string($DOB) . ")";
It looks like you're just missing some quote around your sql query.
Something like
$sql= "INSERT INTO `users`(`Forename`, `Surname`, `Email`, `Username`, `Password`, `DOB`)
VALUES (".$Forename.", ".$Surname.", ".$Email.", ".$Username.", ".$Password.", ".$DOB.")";
Should fix your error.
It's also worth nothing that mysql_query is depreciated and can be pretty unsecure. It might be worth looking at PDO preapred statements if this is something that's going to be used in production. Check out http://php.net/manual/en/ref.pdo-mysql.php and Dream in Code PDO

Shared login session between EasyAppointments and Bootstrap website

This is my first post on stackoverflow, though I have done extensive research using it along with other sources on a regular basis (including the subject I need help with here.)
To be concise, I am working on a shared session/login/register between a client's site and the EasyAppointments scheduling application. While compiling the config.php for the registration form on my client's site I received this error. I have searched everywhere, please help me understand this:
INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles) VALUES(testing, test, 000000000, 000000000, 123 example street, Birmington, Alabama, 00000, , )INSERT INTO `ea_user_settings` (username, password, salt, working_plan, notifications, google_sync, google_token, google_calendar, sync_past_days, sync_future_days) VALUES(TestUser, 0000000000, , , 0, , , , , )
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 ' , 0, , , , , )' at line 2
Here is my config.php code (please excuse my unorthodox variables for sql1/sql2):
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', '####');
define('DB_USER','####');
define('DB_PASSWORD','####');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$mobile_number = $_POST['mobile_number'];
$phone_number = $_POST['phone_number'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip_code = $_POST['zip_code'];
$noteboy = $_POST['notes'];
$privs = $_POST['id_roles'];
$email = $_POST['email'];
$nick = $_POST['nick'];
$password = $_POST['password'];
$salt = $_POST['salt'];
$working_plan = $_POST['working_plan'];
$notifications = $_POST['notifications'];
$google_sync = $_POST['google_sync'];
$google_token = $_POST['google_token'];
$google_calendar = $_POST['google_calendar'];
$sync_past_days = $_POST['sync_past_days'];
$sync_future_days = $_POST['sync_future_days'];
$bang = "INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles)
VALUES($first_name, $last_name, $mobile_number, $phone_number, $address, $city, $state, $zip_code, $noteboy, $privs)";
echo $bang;
$banger = "INSERT INTO `ea_user_settings` (username, password, salt, working_plan, notifications, google_sync, google_token, google_calendar, sync_past_days, sync_future_days)
VALUES($nick, $password, $salt, $working_plan, $notifications, $google_sync, $google_token, $google_calendar, $sync_past_days, $sync_future_days)";
echo $banger;
$result = mysql_query($bang); mysql_query($banger);
if($result) {
echo "Successfully updated database";
} else {
die('Error: '.mysql_error($con));
}
mysql_close($con);
I doubt you're storing phone numbers as integers, so you should be quoting all those zeroes. SQL doesn't like missing values in the VALUES clause, so you need to fix that to default to a format that's appropriate for your fields, such as empty string, a zero or a NULL. You also need to think about escaping too to avoid errors and SQL injection vulnerabilities - using PDO might be good idea if you're early on in your project, and you should definitely switch to mysqli at the very least.
Your check for query failure only looks at your first query - you should check both.
Anyway, here's how you might apply escaping and quoting to avoid the error you're seeing using your current approach:
$bang = "INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles)
VALUES('".
mysql_real_escape_string($first_name)."','".
mysql_real_escape_string($last_name)."','".
mysql_real_escape_string($mobile_number)."','".
mysql_real_escape_string($phone_number)."','".
mysql_real_escape_string($address)."','".
mysql_real_escape_string($city)."','".
mysql_real_escape_string($state)."','".
mysql_real_escape_string($zip_code)."','".
mysql_real_escape_string($noteboy)."','".
mysql_real_escape_string($privs)."')";

Database not getting updated from php

I'm sending data from a form to a php script which should connect to a database and then update the table. It's basically a database of all registered users. For some reason, the database table is not getting updated with the values.
The form code is :
<body>
<div class="header">
Registration
</div>
<div class="content" style="text-align:center";>
<form name="input" action="success.php" method="post"><br>
First name: <input type="text" name="firstname"><br/>
Last name: <input type="text" name="lastname"><br/>
Age: <input type="text" name="age"><br/>
Date of Birth: <input type="text" name="dateofbirth"><br/>
Email: <input type="text" name="email"><br/>
<input type="submit" value="Submit"><br/><br>
</form>
</div>
<br><br><a href="index.html" style="font-size: 22px";>Back</a>
</body>
And the php code I have is:
<?php
$con=mysqli_connect("example.com","myname","123","database1");
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
mysqli_query($sql);
mysqli_close($con);
?>
Can someone please tell me where I'm going wrong?? The Database is not getting updated. There are no values being entered into my table.
Firstly, PLEASE use something like PDO or mySQLi's prepared statements.
Secondly, the database isn't getting updated because you need to concatenate (again, don't do this, please!) the values, like so:
$sql="INSERT INTO user (...) VALUES (".$_POST['firstname'].",".$_POST[]."...)";
This is very dangerous though, so I highly...highly recommend looking into PDO.
Also
The syntax for mysqli_query is wrong as stated in the comments on your post.
Try putting curly braces around the $_POST[...]
Like
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES ('{$_POST[firstname]}','...
change
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
to
$sql="INSERT INTO user
(fname, lname, age, dob, email) VALUES
('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['age']."','".$_POST['dateofbirth']."','".$_POST['email']."')";
Always check for errors when you run SQL statements. You'll never know what's going wrong unless you check whether the query was successful or not, and then print the error.
Also as other folks have commented, please don't include $_GET or $_POST variables directly in your SQL. This exposes you to getting hacked.
Here's an example of the proper way to code this:
<?php
$con=mysqli_connect("example.com","myname","123","database1");
if ($con->connect_error) {
trigger_error($con->connect_error, E_USER_ERROR);
}
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES (?, ?, ?, ?, ?)";
if (($stmt = $con->prepare($sql)) === false) {
trigger_error($con->error, E_USER_ERROR);
}
$stmt->bind_param("sssss", $_POST["firstname"], $_POST["lastname"],
$_POST["age"], $_POST["dateofbirth"], $_POST["email"]);
if ($stmt->execute() === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
$con->close();
?>
Now if there's a problem preparing or executing the query, it'll report it to you.
Create prepared statements is not that hard. Simply copy paste and you are good. I added some extra security with escapeshellarg, which should be more used then it is since prepared statements isn't always 100% secure.
<?php
$firstname = escapeshellarg($_POST["firstname"]);
$lastname = escapeshellarg($_POST["lastname"]);
$age = escapeshellarg($_POST["age"]);
$dateofbirth = escapeshellarg($_POST["dateofbirth"]);
$email = escapeshellarg($_POST["email"]);
$con=mysqli_connect("example.com","myname","123","database1");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_stmt_init($con);
$query = "INSERT INTO user (fname, lname, age, dob, email) VALUES (?, ?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, "sssss", $firstname, $lastname, $age, $dateofbirth, $email);
if(mysqli_stmt_execute($stmt))
{
mysqli_close($con);
}
?>
Note that "sssss" stands for Strings. If your age is an int variable then use "ssiss" instead.
PS. A simple mistake I had once with WAMP (Apache) was that the user didn't have the right privileges. It took me way too many hours to find that, don't do the same mistake ;)
Tested
I created a table with the same entries that you posted and have come to this conclusion.
But first; as others have pointed out and it's been said time and time again, the use of MySQL_ is being deprecated and will be deleted in the very near future. Therefore using MySQLi_ and/or PDO is strongly and highly recommended.
To quickly fix your problem, you are not telling it to connect to your DB when passing query.
Change:
mysqli_query($sql);
to:
mysqli_query($con, $sql);
and it will work. It worked for me, therefore theoretically it will work for you also.
I suggest you use Bill Karwin's version for better security.

Form data not being sent to MySql database

Have a simple registration form that is being linked to a php file in order to send the info to a database but everytime i try it the data isnt showing up in the phpMyAdmin database??
<?php
$name = $_POST['name'];
$address = $_POST['address'];
$number = $_POST['number'];
$email = $_POST['email'];
$details = $_POST['details'];
$user="root";
$password="secure";
$database="darrenweircharity";
mysql_connect("localhost",$user,$password);
#mysql_select_db($database) or die ("Unable to select database");
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('$name', '$address', '$number', '$email', '$details' NOW())";
mysql_query($query);
mysql_close();
?>
Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. 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.
Try with:
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('" . $name . "', '" . $address . "', '" . $number . "', '" . $email . "', '" . $details . "');";
You have NOW() at the end of the query that shouldn't be there.
Also note that your code has an SQL injection vulnerability (see mysql_real_escape_string()), I suggest you to prepare queries via PDO.
protect from possible SQL injection:
$name = mysql_real_escape_string($name);
$address = mysql_real_escape_string($address);
$number = mysql_real_escape_string($number);
$email = mysql_real_escape_string($email);
$details = mysql_real_escape_string($details);
replace with:
$query = "
INSERT INTO registrationdetails (`name`, `address`, `number`, `email`, `details`)
VALUES ('$name', '$address', '$number', '$email', '$details')");
$query = "
INSERT INTO registrationdetails (name, address, number, email, details, date_time)
VALUES ('{$name}', '{$address}', '{$number}', '{$email}', '{$details}', NOW())
";
Replace the date_time with your column_name. And remember to escape all submitted values with mysql_real_escape_string before inserting them into the database.

Categories