I keep getting "Error Querying Database" in PHP code - php

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.

Related

How to Select Database for an INSERT INTO statement

I have multiple SQL databases and I need to insert data into one of them. I am not sure how to select the database.
The following code was working when I only had 1 database, but now that there are multiple databases, this code no longer works.
$sql = "INSERT INTO users (username, first_name, last_name, email,
password, hash, avatar) "
. "VALUES
('$username','$first_name','$last_name','$email','$password', '$hash',
'$avatar')";
I want to write the above data into a table in a specific database.
You can set it while connection or just:
$sql = "INSERT INTO databasename.users (username, first_name, last_name, email, password, hash, avatar) "
. "VALUES ('$username','$first_name','$last_name','$email','$password', '$hash', '$avatar')";
Either of these might work
Use 'DBName.users' in the query instead of 'users'.
Execute the query 'use DBName;' before the insert query.

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 inserting into two tables from one form not working

Below is my php code, which should take the data from my form and put it into two tables in my database. However I keep getting an SQL syntax error by the values, I was originally putting the values in ' ' however I got the error so then I changed the values to backticks . But that still didnt seem to make much difference. Im receiving the error, however street, city, county, postcode, tel and date of birth are all inputting into the users table. But nothing else, and nothing is going into the members table.
Any help would be greatly appreciated. Many thanks
$con = mysql_connect("localhost", "alex", "");
if(!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("gym", $con);
//** code above connects to database
$sql ="INSERT INTO users (First_Name, Last_Name, Street, City, County, Postcode, Telephone, Email, Date_Of_Birth, Gender)
VALUES
(`$_POST[FirstName]`,
`$_POST[LastName]` ,
`$_POST[Street]`,
`$_POST[City]`,
`$_POST[County]`,
`$_POST[Postcode]`,
`$_POST[Tel]`,
`$_POST[Email]`,
`$_POST[Date_Of_Birth]`,
`$_POST[Gender]`)";
$result1=mysql_query($sql,$con);
$sql1 = "INSERT INTO members( Membership_Number, Membership_Type, Membership_Referal, Trainer_Required, Medical_Informaton, Contract, Card_Holder_Name, Bank, Card_Number, Sort_Code, valid, Exp, Security_Number
VALUES
(`$_POST[MembershipNumber]`,
`$_POST[MembershipType]`,
`$_POST[MembershipReferral]`,
`$_POST[TrainerRequired]`,
`$_POST[MedicalInformation]`,
`$_POST[Contract]`,
`$_POST[BankBranch]`,
`$_POST[CardHolderName]`,
`$_POST[CardNUMBER]`,
`$_POST[Expiry]`,
`$_POST[SecurityCode]`)";
$result2=mysql_query($sql1,$con);
//***** code below is error message if it doesnt work
if($result1 && $result2){
printf("window.alert(\"New Record Added!\");");
}
else
{
echo "Error:". mysql_error()."";
}
mysql_close($con)
?>​
Remove backtics and add `single quote` to values parameter
User SQL query like.
$sql = "INSERT INTO users (First_Name, Last_Name) VALUES('".$_POST[FirstName]."','".$_POST[LastName]."')";
You must pass parameter between {$_POST['variable']} like this:
$sql1 = "INSERT INTO members( Membership_Number, Membership_Type, Membership_Referal, Trainer_Required, Medical_Informaton, Contract, Card_Holder_Name, Bank, Card_Number, Sort_Code, valid, Exp, Security_Number
VALUES
(`{$_POST['MembershipNumber']}`,
`{$_POST['MembershipType']}`,
`{$_POST['MembershipReferral']}`,
`{$_POST['TrainerRequired']}`,
`{$_POST['MedicalInformation']}`,
`{$_POST['Contract']}`,
`{$_POST['BankBranch']}`,
`{$_POST['CardHolderName']}`,
`{$_POST['CardNUMBER']}`,
`{$_POST['Expiry']}`,
`{$_POST['SecurityCode']}`)";
please use ' not use `
just like
'$_POST[value]', ........, ........

mysqli_query returning error

Hi I'm very new to php and my query to my mysql database is returning an error. My connection is fine, but there's something wrong with my query. I've run it through php validators but they can't find any errors. Any help would be appreciated. Thanks in advance. Here's my code.
<?php
$dbc=mysqli_connect('url','username','password')
or die('error connecting');
$query = "INSERT INTO mailing_list (first_name, last_name, email_address)" .
"VALUES ('one','two','three')";
$answer = mysqli_query($dbc,$query)
or die('error querying');
mysqli_close($dbc);
?>
You have no space in between (first_name, last_name, email_address) and VALUES. MySQL would recognize that as one word rather than two. So add that in and it should work, like this:
$query = "INSERT INTO mailing_list (first_name, last_name, email_address) " .
"VALUES ('one','two','three')";
you have the connection almost right but where is your database selector,also check your php extension whether it is mysql or mysqli

Having trouble using MySQLi INSERT queries

Okay, so I'm updating my site from MySQL to MySQLi, which means I have to re-code some of the database stuff.
I looked on php.net on how to use MySQLi queries to insert data into a table and did exactly what they said to, but no luck.
Here's my connection variable:
$con = mysqli_connect("localhost", "username", "password", "database");
And here is the code to insert the data:
mysqli_query($con, "INSERT INTO users ('user', 'pass', 'email') VALUES ('$user', '$pass', '$email')");
It doesn't reply with any errors, and it just takes me to the intended landing page. It doesn't actually add the data to the table though.
Any ideas?
As answered above, removing the quotes from the column names will solve your problem:
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('$user', '$pass', '$email')");
But I also noted that your script is vulnerable against SQL injection attacks.
In MySQLi you can prepare your statements before execution, so you will be sure that no one will inject SQL commands in your database.
If you don't want to prepare each sql statements before execution, at least use the mysqli_real_escape_string function, that will protect your system against SQL injection too. Use like that:
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('" . mysqli_real_escape_string($user) . "', '" . mysqli_real_escape_string($pass) . "', '" . mysqli_real_escape_string($email) . "')");
remove single quotes from column names
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('$user', '$pass', '$email')");
OR
mysqli_query($con, "INSERT INTO users (`user`, `pass`, `email`) VALUES ('$user', '$pass', '$email')");

Categories