pg_query INSERT INTO not working - php

I have a setup With Apache24, php environment and postgresql database.
I'm trying to populate some columns (not all) in db table with values, but it is not working as I would expect.
I get the following error/warning and db is not populated:
Warning: pg_query(): Query failed: ERROR: syntax error at or near "c329a92850f6d539dd376f4816ee2764517da5e0235514af433164480d7a" LINE 1: ...word, salt) VALUES (DEFAULT, cff#jjj.no, per, 8254c329a92850... ^ in C:\Users\Public\Server\Apache24\htdocs\eMe\newuser.php on line 34
Any support on this is highly appreciated. I have searched for similar questions but not been able to interpret the answers into my context.
<?php
# Registration form input to postgresql user table in myDB
session_start();
# Retrieve data from input form
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
# Concatenate and hash password with salt
require_once(dirname(__DIR__).'\eMe\saltgenerator.php');
global $randString;
#$randString = pg_escape_string($randString);
$isalt = pg_escape_string($randString);
$saltandpassword = $isalt. $password;
$hashedpassword = hash('sha256', $saltandpassword, false);
$username = pg_escape_string($username);
$email = pg_escape_string($email);
$hashedpassword= pg_escape_string($hashedpassword);
# Insert data into Postgresql database
# INSERT INTO table_name (column1, column2, column3 .....) VALUES (value1, value2, value3....)
include_once(dirname(__DIR__).'\eMe\config.php');
$query = "INSERT INTO users (userid, mailaddress, username, userpassword, salt) VALUES (DEFAULT, $email, $username, $hashedpassword, $isalt)";
#$result =
#pg_query_params($query);
pg_query($query);
?>
I have tried to include quotes and backtick quotes as described on this link but it does not solve the problem. The error/warning is slightly different though:
Warning: pg_query(): Query failed: ERROR: syntax error at or near "`" LINE 1: INSERT INTO users (userid, `mailaddress`, `username`, `use... ^ in C:\Users\Public\Server\Apache24\htdocs\eMe\newuser.php on line 30

The only problem in your code is you didn't figure out yet that when writing that:
$username = pg_escape_string($username);
$username gets escaped for injection, which is good, but this will add necessary quotes inside the value, not around the value (see Whats does pg_escape_string exactly do? for more).
So in the query, quotes are needed around the literal text values in addition to escaping the contents, as in the following:
$query = "INSERT INTO users (userid, mailaddress, username, userpassword, salt)
VALUES (DEFAULT, '$email', '$username', '$hashedpassword', '$isalt')";
(given that the variables in this query have already been passed through pg_escape_string)

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?

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.

php script not connecting to MySQL database

I have a php "verifyconect.php" script which has my connection to the server. When I fill out my form page it is meant to write the data to the MySQL database but it does not do this. I have also changed the hostname to "localhost" although this is being hosted on the web. I inputted the server hostname which works with my FTP software but no change occurs. Please what am I getting wrong.
verifyconect.php
<?php
$link = mysql_connect ("hostname", "###", "###");
mysql_select_db ("dbtable", $link);
?>
VerifyLogin.php
<?php
include("verifyconect.php");
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
$insert = 'INSERT INTO verifytable (username, email, password, confirm_password) VALUES ("'.$username.'", "'.$email.'", "'.$password.'", "'.$confirm_password.'")';
mysql_query($insert);
?>
You are switching up the single and double quotes.
Suppose
username = john
email = john#example.com
password = hell0w0rld
confirm = hell0w0rld
then the query will be this:
INSERT INTO verifytable (username, email, password, confirm_password) VALUES ("john", "john#example.com", "hell0world", "hell0w0rld")
Using double quotes in SQL queries give a syntax error. To use literal values in SQL queries, you must use single quotes.
So if you rewrite the line with your $insert variable to the following:
$insert = "INSERT INTO verifytable (`username`, `email`, `password`, `confirm_password`) VALUES ('".$username."', '".$email."', '".$password."', '".$confirm_password."')";
you will be good.
Also note that I surrounded the SQL table column names with backticks, so if you use a keyword (like password) as column name, it won't give syntax errors.
Update
It seems that in some cases using double quotes for (literal) values to insert into a SQL table, sometimes will work too. However, according to this answer, you better stick to single quotes.

inserting data from a form into your mysql database using php

i used this code
<?php
$conn = new PDO("mysql:host=localhost;dbname=CU4726629",'CU4726629','CU4726629');
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
header('Location: reviews.php');
?>
but it keeps giving me this error
Parse error: syntax error, unexpected T_VARIABLE in
/home/4726629/public_html/check_login.php on line 5
Take this for an example:
<?php
// insert some data using a prepared statement
$stmt = $dbh->prepare("insert into test (name, value) values (:name, :value)");
// bind php variables to the named placeholders in the query
// they are both strings that will not be more than 64 chars long
$stmt->bindParam(':name', $name, PDO_PARAM_STR, 64);
$stmt->bindParam(':value', $value, PDO_PARAM_STR, 64);
// insert a record
$name = 'Foo';
$value = 'Bar';
$stmt->execute();
// and another
$name = 'Fu';
$value = 'Ba';
$stmt->execute();
// more if you like, but we're done
$stmt = null;
?>
You just wrote a string in your above code:
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
Above answers are correct, you will need to concat the strings to form a valid sql query. you can echo your $sql variable to check what is to be executed and if is valid sql query or not. you might want to look in to escaping variables you will be using in your sql queries else your app will be vulnerable to sql injections attacks.
look in to
http://php.net/manual/en/pdo.quote.php
http://www.php.net/manual/en/pdo.prepare.php
Also you will need to query you prepared sql statement.
look in to http://www.php.net/manual/en/pdo.query.php
A couple of errors:
1) you have to concat the strings!
like this:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
2) you are not using the PDO at all:
after you create the "insert" string you must query the db itself, something like using
$conn->query($sql);
nb: it is pseudocode
3) the main problem is that this approach is wrong.
constructing the queries in this way lead to many security problems.
Eg: what if I put "moviename" as "; drop table review;" ??? It will destroy your db.
So my advice is to use prepared statement:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$fill_array = array($_POST['username'], $_POST['moviename'], $_POST['ratings']);
$q->execute($fill_array);
You forgot dots:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
and fot the future for now your variables are not escaped so code is not secure
String in a SQL-Statment need ', only integer or float don't need this.
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ('".$_POST['username']."','".$_POST['moviename']."','".$_POST['ratings']."')";

INSERT PHP Statement not working

So, I'm not exactly sure what the problem is, but, when I try to INSERT into a table, it doesn't work.
All the variables are working. I've echoed and tested them, they are working.
$username = $_SESSION['username'];
$update = $_GET['update'];
mysql_query("INSERT INTO updates (username, update) VALUES ('$username', '$update')");
So it must be a problem with my mySQL query. This mySQL query is one of two in the .php folder. If that makes any difference.
Error in SQL
There is an error in your SQL. You cannot use MySQL keywords in column names without quoting them.
In this case update needs to be enclosed in backticks:
$query = "INSERT INTO updates (`username`, `update`)
VALUES ('$username', '$update')";
SQL injection
Your code is susceptible to SQL injection attacks. You should escape quoted strings that are placed into an SQL statement with mysql_real_escape_string() or bind your data using PHP PDO prepared statements.
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
Putting it together
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
$query = "INSERT INTO updates (`username`, `update`)
VALUES ('$username', '$update')";
I have written little SQLFiddle for you so you can see this in action: http://sqlfiddle.com/#!2/c25b1/1
You need to escape the data you are about to insert. You also want to separate the string from the variables.
Try something like this:
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
mysql_query("INSERT INTO `updates` (username, update) VALUES ('" . $username . "', '" . $update . "')") or die(mysql_error());
That's untested but should work.
mysql_error() is the best way but you can also echo your query and run it directly against the database to see what is the problem.
$username = $_SESSION['username'];
$update = $_GET['update'];
$query = "INSERT INTO updates (username, update) VALUES ('$username', '$update')";
mysql_query($query);
echo "My Query : $query";
try this:
$username = $_SESSION['username'];
$update = $_GET['update'];
mysql_query("INSERT INTO updates (username, update) VALUES ('+$username', '+$update')");
also is better is create a variable to put the query string and then you make the query

Categories