Database not getting updated from php - 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.

Related

MySQL not able to execute INSERT INTO [table]. Column count doesn't match value count at row 1

I'm trying to pull information from an HTML form and put this into a database using the following code:
$link = mysqli_connect("localhost", "user", "password", "MyDB");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob' '$addr')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It was working, and I've managed to get 2 test runs in, but now I'm getting the following error at the top of my submission page
ERROR: Could not able to execute INSERT INTO MyDB (name, email, dob,
address) VALUES ('test name', 'test#email.com', '2003-02-01'
'address'). Column count doesn't match value count at row 1
I have another variant of this which sends a PHP email, which is the file I'm using to base this database connection on.
There is also an autoincrement on ID column which is set as the primary key in the database if that makes a difference? SQL isn't my strong point unfortunately!
Given the syntax error you have in your query, being a missing comma in '$dob' '$addr'; you are open to an SQL injection and should be using a prepared statement.
Therefore, I am submitting this complementary answer for your own safety.
Here is an example of a prepared statement using the MySQLi API.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
// assuming these are the POST arrays taken from your HTML form if you're using one.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$addr = $_POST['addr'];
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
$stmt = $link->prepare($sql) or die("Failed Execution");
$stmt->bind_param('ssss', $fullname, $email, $dob, $addr);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
References:
How can I prevent SQL injection in PHP?
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Foonotes:
If using the following failed because of the AI'd column:
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
You may also try: (I used id as the AI'd column as an example)
$sql = ("INSERT INTO interest (id, name, email, dob, address) VALUES ('', ?, ?, ?, ?)");
This could be the case, as I have seen this type of SQL failure behaviour before.
You have missed comma here:
VALUES ('$fullname', '$email', '$dob' '$addr')
Thus (as it was clearly said in error text) column count doesn't mach values count.
It should be
VALUES ('$fullname', '$email', '$dob', '$addr')
You missed a comma
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob', '$addr')";
^here
You missed a comma:
VALUES ('$fullname', '$email', '$dob' '$addr')

I keep getting "Error Querying Database" in PHP code

Looks like I'm connecting to the server just fine. The problem seems to happen when it runs the query. It keeps saying
Error Querying Database
Here is my code:
<?php
$dbc = mysqli_connect('localhost', 'elvis_store')
or die('Error connecting to MySQL server.');
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$query = "INSERT INTO email_list (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
mysqli_query($dbc, $query)
or die('Error querying database.');
echo 'Customer added.';
mysqli_close($dbc);
?>
You are getting this error because in your MySQLi connection you only give a location and username. You do not give a database name to be used. if you have no password, you need to write your connection like this:
$dbc = mysqli_connect('localhost', 'elvis_store', NULL, 'dbName)
or
$dbc = mysqli_connect('localhost', 'dbUsername', NULL, 'elvis_store')
if "elvis_store" is the database name and not the username. Remember, a mysqli connection is: mysqli_connect(dbLocation, dbUsername, dbPassword, dbName).
Also, as Ed has pointed out in another answer, there is also a syntax error in your MySQL statement. Here is the snippet from Ed's answer:
$query = "INSERT INTO email_list (first_name, last_name, email) " . "VALUES ('$first_name', '$last_name', '$email')";
You have multiple problems.
Problem 1: Syntax error
Your query has a typo (a missing space). Your query code
$query = "INSERT INTO email_list (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
produces this query:
INSERT INTO email_list (first_name, last_name, email)VALUES ('$first_name', '$last_name', '$email')
-- ^ syntax error, missing space
To fix it, change your code to this:
$query = "INSERT INTO email_list (first_name, last_name, email) " .
"VALUES ('$first_name', '$last_name', '$email')";
At least for testing purposes, you probably should look at the output of mysqli_error() instead of using a generic message like Error querying database. Even in production, you'll want to trap and log the real error somehow.
Problem 2: You don't select a database
Edit: I missed this in my first glance at your question, but as Stephen Cioffi points out, you also need to select a database before running your query. You can do this with the schema parameter to mysqli_connect() or by using mysqli_db_select().
Both of these issues—the typo and the failure to select a database—will cause problems; you must fix both.
Problem 3: Huge SQL Injection Vulnerability
This is not strictly part of the answer, but it's important. You are wide open to SQL injection. You need to use prepared statements. Otherwise, you are going to get hacked. Imagine that the POSTed firstname is this:
', (SELECT CONCAT(username, ',', password) FROM users WHERE is_admin = 1), 'eviluser#example.com') --
Your query becomes (with some added formatting):
INSERT INTO email_list (first_name, last_name, email)
VALUES ('',
(SELECT CONCAT(username, ',', password) FROM users WHERE is_admin = 1),
'eviluser#example.com'
) -- ', 'value of lastname', 'value of email')
Then, when you email your users, somebody's going to get an email with a recipient like
"Duke,mySup3rP#ssw0rd!" <eviluser#example.com>
And... you're hosed.
(Hopefully, you're salting and hashing passwords, but still, this is disastrous.) You must use prepared statements.

Why does my php form keep yielding empty rows in mysql?

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.

mysqli insert into function not returning true or false

Hey there first time poster here. I'm creating a registration form using php and mysqli, and everything is working fine up until the actual insert function.
I've checked and double checked and triple checked the variable names within the query, they are correct, the form inputs are reaching the function as well, but for some reason at £this->connect->query($query) it refuses to work. I've tried countless different ways to execute the actual query, each one returning false. I'm at my wits end here, hopefully someone can help!
function insertNewRecord($fname, $lname, $pass, $email, $mob, $school, $location, $connumb)
{
$query = "INSERT INTO 'dbusers'
(firstName, lastName, password, emailaddress, mobnumb, school, campus, connumb)
VALUES ($fname, $lname, $pass, $email, $mob, $school, $location, $connumb)";
if(!$this->connection->query($query)) {
echo $query;
}
}
edit: I figured it out, I forgot to auto_increment the userid within the table. I've been stuck on this for hours, I feel like such an idiot.
Thanks for your time
Try using your query in the following form:
$query = "INSERT INTO `dbusers`
(`firstName`, `lastName`, `password`, `emailaddress`, `mobnumb`, `school`, `campus`, `connumb`)
VALUES ('$fname','$lname', '$pass', '$email', '$mob', '$school', '$location', '$connumb')";
But this is not the correct way to go, you should use prepared statements to prevent SQL injection. See the manual

problems, custum wrap (class) around PDO, doesn't work

DB::construct();
$STH = DB::prepare('INSERT INTO users (username, password, email, activationkey) VALUES (?, UNHEX(?), ?, ?)');
var_dump($STH);
$result = $STH->execute(array('test', 'nils', 'test#mail.com', '227a038fe9c81515b514cb152188e95c'));
echo "working? <br />";
if($result == false) echo 'noooo...';
It outputs and doesn't put anything in the database. Works with a similare code with DPO just without my DB class. But I doesn't get any errors. Anyone have an idea what the problem could be?
object(PDOStatement)#2 (1) { ["queryString"]=> string(87) "INSERT INTO users (username, password, email, activationkey) VALUES (?, UNHEX(?), ?, ?)" }
working? <br /> noooo...
The code seems OK (ofcourse, don't know what you've done under the hood). Doesn't PDO itself generate an error / what does var_dump($STH->errorInfo()); say?

Categories