PHP MySQL Insert issue - php

I am trying to complete an SQL insert query using php. The error I am returned with is:
SCREAM: Error suppression ignored for
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\sign\db.php on line 28
I am using wamp and I have tested the query directly in php myadmin and it works fine. I don't know what the problem is.
Thanks in advance.
<?php
//variables for db
$username = "root";
$password = "";
$hostname = "127.0.0.1";
$dbname = "site";
//connection to the database
$con = mysql_connect($hostname, $username, $password);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
mysql_select_db($dbname, $con);
mysql_query("INSERT INTO users (full_name, first_name, dob, star_sign) VALUES ("test","test", "test", "test");";
?>

use single quotes instead.
mysql_query("INSERT INTO users (full_name, first_name, dob, star_sign) VALUES ('test','test', 'test', 'test');";

You need to backslash the quotes, here, else you close the statement
mysql_query("INSERT INTO users (full_name, first_name, dob, star_sign) VALUES (\"test\",\"test\", \"test\", \"test\");";
Alternatively you can replace them for single quotes

You need to fix your quotes:
// use single quotes
mysql_query("INSERT INTO users (full_name, first_name, dob, star_sign)
VALUES ('test','test', 'test', 'test');";
// Or...
// escape your double quotes
mysql_query("INSERT INTO users (full_name, first_name, dob, star_sign)
VALUES (\"test\",\"test\", \"test\", \"test\");";
What is happening (especially if you pay attention to syntax highlighting of the code in your question), is that simply using double quotes will end the string.
To fix this, you can use single quotes, or escape the double quotes.

Related

pg_query INSERT INTO not working

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)

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.

second mysqli_query not working

I have the follow php script for registering a user
<?php
require_once "setting.php";
extract($_REQUEST);
$link = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if (mysqli_connect_errno()){
echo "Connection failed".mysqli_connect_error();
}
$initQuery = "SELECT * FROM users WHERE email = ".$email;
$initResult = mysqli_query($link, $initQuery);
$dbResults = mysqli_fetch_array($initResult, MYSQLI_ASSOC);
if($dbResults == null ){
echo('in the if statement');
$userId = uniqid();
echo($userId);
$query = "INSERT INTO users(email, password, userId) VALUES ($email, $password, $userId )";
echo($query);
$addResult = mysqli_query($link, $query);
echo($addResult);
}
mysqli_free_result($initResult);
mysqli_free_result($addResult);
mysqli_close($link);
?>
The second mysqli_query is not adding a user, I've checked the syntax of the sql statement and it works fine. Does anyone have any ideas?
Also I was thinking about maybe trying to write a mysqli_multi_query to run both queries. I've read that the multi_query will return false if the first query fails, is there anyway to have it execute the second query if the first one fails and not execute the second query if the first one succeeds?
For the love of God, at least put the string values inside quotes if not use prepared statements
"INSERT INTO users(email, password, userId) VALUES ($email, $password, $userId)"
Is invalid. Those string values should be inside quotes
"INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId')"
Please read this before you implement the solution given above:
How can I prevent SQL injection in PHP?
At the very least, please escape the values with mysqli_real_escape_string
Use quotes for your values.
$query = "INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId' )";
$addResult = mysqli_query($link, $query);
If you are facing error than use die function to get the error detail.
$addResult = mysqli_query($link, $query) or die(mysqli_error($link));
It will show you the error also.
Hope this works:
$query = "INSERT INTO users (email, password, userId) VALUES ('$email', '$password', $userId)";
Give a space after table name and all the variables in single quote. :)
UPDATE
Space is not mandatory to give, but would be good for better coding :)
Try to put the values inside quotes.
$query = "INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId' )";
To understand why quotes are mandatory i give an example :).
Mysql supports SELECT from another table for inserted values like in the code below:
INSERT INTO users (email, password, userId)
VALUES
((SELECT email FROM user_info WHERE id = '$userId'),'$password','$userId'))

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.

How to insert data into MySQL using MySQLi?

I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.

Categories