Inserting Integer value into mysql int using INSERT - php

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.

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.

Return the ID of the last value inserted SQL

I'm inserting data into members table, after I've inserted it I want to get the userID of the information just inserted. Whats the best way about doing this ?
My php code
//Insert info into database
$sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')";
//Run a query to check if data has been inserted correctly.
$records = mysqli_query($connect, $sql);
I did try this SQL but was getting errors
$sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')"; SELECT SCOPE_IDENTITY(userID);
Assuming $connect as the variable holding your connection information, which seems legit, you can get the value of the last id with:
$user_id = mysqli_insert_id($connect);
This is something you can do from the PHP MySQLi interface, rather than directly from SQL!

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]', ........, ........

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')");

Column Count vs Value Count on insert statement - PHP/MySQL

I am working on building an employee database but seem to have run into an interesting issue.
When I run my query to add a new user/employee, I get the error:
Column count doesn't match value count at row 1
From what I have researched, this seems to be an error with inserting more/less values than what is declared in the first part of an insert statement example:
INSERT INTO table (col1, col2) VALUES (val1, val2, val3)
The thing is though, I have looked over my query and the columns and values match perfectly (count wise). I have even looked for things in my query such as missing quotes, commas, etc.
Here is my code (query):
$db->query("INSERT INTO userdata (
Username,
Email,
Phone,
Password,
FirstName,
LastName,
Address,
City,
State,
Zip,
JobTitle,
UserGroup,
JobStatus,
Points,
Status,
BirthDate,
HireDate,
HourlyRate,
DateAdded,
SSN
) VALUES (
'$Username',
'$Email',
'$Phone',
'$Password',
'$FirstName',
'$LastName',
'$Address',
'$City',
'$State',
'$Zip',
'$JobTitle',
'$Group',
'$JobStatus',
0,
'$Status',
'$BirthDate',
'$HireDate',
'$HourlyRate'
'$TodaysDate',
'$SSN'
)") or die(mysqli_error($db));
Some things to note:
This not all of the columns in the table have data inserted here (I think its possible to do this and things such as auto incrementing ID's will fill themselves in and others will be left blank)
From the variable dumps I have done, all of these variables are valid.
I am really confused about this and any help would be appreciated.
Check the following portion again:
INSERT INTO userdata(...,
JobStatus,
UserGroup,
Points,
UserGroup,
Status,
.....
,)VALUES(...,
$JobStatus',
0,
'$Group',
'$Status',
......
)
In values(, ?, ?, ?), after jobstatus, there should be UserGroup and then Points. And UserGroup appeared twice.

Categories