php script not connecting to MySQL database - php

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.

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 MySQL Insert issue

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.

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