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]', ........, ........
Related
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.
Recently i was searching for unique username registration using php.. I came across a piece of code which i am displaying below:
<?php
$fname=trim($_POST['fname']);
$lname=trim($_POST['lname']);
$email=trim($_POST['email']);
$usn=trim($_POST['usn']);
$dept=trim($_POST['dept']);
$pass=trim($_POST['pass']);
$tel=trim($_POST['tel']);
$dbh = mysql_connect('localhost', 'root','') or die("<h3 style=\"color:red;\" align=\"center\">SERVER ERROR</h3>");
mysql_select_db('fy') or die("<h3 style=\"color:red;\" align=\"center\">SERVER ERROR</h3>");
$error= mysql_query("SELECT * FROM stud WHERE email='$email' OR usn='$usn' OR tel='$tel'") or die (mysql_error());
if (mysql_num_rows($error) > 0);
{
die ("Sorry! Either email, usn or tel already exists!");
}
$query="INSERT INTO stud (fname, lname, email, tel, usn, dept, pass) VALUES ('$fname', '$lname', '$email', '$tel', '$usn', '$dept', '$pass')";
mysql_query($query);
$query="INSERT INTO log VALUES ('$usn','$pass',0,0)";
mysql_query($query);
print("REGISTERED");
?>
LOGIN<br />
At this moment my database is completely empty. I've just created the database stud with the desired columns. Now the problem is when i try to register using my registration page, it gives me the error i specified in die that is
"Sorry! Either email, usn or tel already exists!"
How is this possible if there are no values in the database. In the registration form I've given
action="register.php"
as a processing file. Also I've tried with mysql_fetch_assoc(), but i get the same error. Any help is appreciated. Thank you .
Your first problem is that, as John Conde states, your code is vulnerable to SQL injection attacks.
Your second problem, and to answer your question, is probably because you have this:
if (mysql_num_rows($error) > 0);
instead of this:
if (mysql_num_rows($error) > 0)
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
I am unable to insert data. The error is:
Error: Unknown column '' in 'field list'
It is simpy an HTML form page and data is taken by the user to insert in a database dB.
Help is truly required. I am unable to get the error things. I am a newbie.
<?php
$con=mysqli_connect("localhost", "root", "root","dB");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$enrollno=$_POST['enrollno'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$fathername=$_POST['fathername'];
$coursename=$_POST['coursename'];
$yearsem=$_POST['yearsem'];
$facultyno=$_POST['facultyno'];
$hostel=$_POST['hostel'];
$roomno=$_POST['roomno'];
$email=$_POST['email'];
$mobileno=$_POST['mobileno'];
$peradd=$_POST['peradd'];
$district=$_POST['district'];
$state=$_POST['state'];
$amount=$_POST['amount'];
$pwd=$_POST['pwd'];
$tnc=$_POST['tnc'];
$sql="INSERT INTO registration (enrollno, fname, lname, fathername, coursename, yearsem, facultyno, hostel, roomno, email, mobileno, peradd, district, state, amount, pwd, tnc) VALUES ('$enrollno',`$fname`,`$lname`,`$fathername`,`$coursename`,`$yearsem`,`$facultyno`,`$hostel`,`$roomno`,`$email`,`$mobileno`,`$peradd`,`$district`,`$state`,`$amount`,`$pwd`,'$tnc')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
You are using backticks[used for columns] for variables. Make use of single quotes. Try the below code
$sql="INSERT INTO registration (enrollno, fname, lname, fathername, coursename, yearsem, facultyno, hostel, roomno, email, mobileno, peradd, district, state, amount, pwd, tnc) VALUES ('$enrollno','$fname','$lname','$fathername','$coursename','$yearsem','$facultyno','$hostel','$roomno','$email','$mobileno','$peradd','$district','$state','$amount','$pwd','$tnc')";
The values in the INSERT INTO query must be enclosed with single quotes ' not backticks and not a mixture of both. Backticks can only be used on the field and table name.
$sql="INSERT INTO registration (enrollno, fname, lname, fathername, coursename, yearsem, facultyno, hostel, roomno, email, mobileno, peradd, district, state, amount, pwd, tnc) VALUES ('$enrollno','$fname','$lname','$fathername','$coursename','$yearsem','$facultyno','$hostel','$roomno','$email','$mobileno','$peradd','$district','$state','$amount','$pwd','$tnc')";
Side note: your code is vulnerable to SQL Injection. Consider using a Prepared Statement with bound parameters instead of concatenating user input into the query.
I'm trying to insert a new record in a MySQL database from PHP, which I've done a million times before, but for some reason, I can't get it to work this time, and it really bugs me.
Inserting strings into all the varchar collumns are going great, but when I get to inserting a value into the int column, I get an error telling me that I have a syntax error.
Basically, the first query works just fine, but the second one returns the error, and as you can see, I've made damn sure it really is an integer I'm trying to insert.
I hope somebody can help. I'm really starting to develop a headache over this :/
$groupId2 = 5;
$groupId = (int)$groupId2;
if(!mysqli_query($link, "INSERT INTO contestants (firstName, lastname, email) VALUES ('$firstName', '$lastName', '$email')"))
echo "First: " . mysqli_error($link);
if(!mysqli_query($link, "INSERT INTO contestants (firstName, lastname, email, group) VALUES ('$firstName', '$lastName', '$email', '$groupId')"))
echo "Second: " . mysqli_error($link);
group is a mysql keyword use back quotes around it
"INSERT INTO contestants (firstName, lastname, email, `group`)
VALUES ('$firstName', '$lastName', '$email', '$groupId')"
The error is because you surrounded your int with ' ', you need to get rid of your apostrophes and it will work just fine.
if(!mysqli_query($link,
"INSERT INTO contestants
(firstName, lastname, email, group) VALUES
('$firstName', '$lastName', '$email', $groupId)"))
^^^^^^^^^
To clarify, when inserting numerical fields you do not need them.
According to pst this is wrong, although, the fact you do not need single quotes is still correct.