MySQL query failing due to reserved keyword? - php

Edit: If you're coming here from Google, this issue is a result of the word int being a reserved keyword in PHP. See the end of the accepted answer.
I'm still learning PHP/MySQL and for the life of me I can't figure out what's wrong with my code.
I'm trying to take some data from an html page and add it to a table in my database. I'm passing the data with a GET request, then retrieving it with PHP's $_GET.
I've tested this and the variables are passed correctly to the PHP script but they don't appear in the database. The script dies on this line:
mysql_query($query) or die('data entry failed');
$database='a9293297_blog';
$con = mysql_connect('mysql2.000webhost.com','my_username','my_password');
mysql_select_db($database,$con) or die('failed to connect to database');
$username = $_GET['username'];
$password = $_GET['password'];
$charName = $_GET['charName'];
$sex = $_GET['sex'];
$class = $_GET['class'];
$race = $_GET['race'];
$str = $_GET['str'];
$sta = $_GET['sta'];
$dex = $_GET['dex'];
$int = $_GET['int'];
$cha = $_GET['cha'];
$query = "INSERT INTO Players (username, password, charName, sex, class, race, str, sta, dex, int, cha)
VALUES ('" . $username . "', '" . $password . "', '" . $charName . "', '" . $sex . "', '" . $class . "', '" . $race . "', '" . $str . "', '" . $sta ."', '" . $dex . "', '" . $int . "', '". $cha . "')";
mysql_query($query) or die('data entry failed'); // Fails here
mysql_close($con);

To know better what's wrong with your SQL query, use mysql_error():
mysql_query($query) or die(mysql_error());
Escape your string variables with mysql_real_escape_string(). Example:
$query = "INSERT INTO MYTABLE(MYFIELD) VALUES ('".mysql_real_escape_string($myVar)."');
EDIT
int seems to be a reserved MySQL keyword. Escape it with backquotes:
INSERT INTO Players (username, password, ..., str, sta, dex, `int`, cha) ...

im not sure but try this
Your Code
$query="INSERT INTO Players (username, password, charName, sex, class, race, str, sta, dex, int, cha)VALUES ('".$username."', '".$password."', '".$charName."', '".$sex."', '".$class."', '".$race."', '".$str."', '".$sta."', '".$dex."', '".$int."', '".$cha."')";
In this code
$query="INSERT INTO Players (username, password, charName, sex, class, race, str, sta, dex, int, cha)VALUES ('$username', '$password', '$charName', '$sex', '$class', '$race', '$str', '$sta', '$dex', '$int', '$cha')";
Maybe this helps if you remove " and .

Related

Can't insert now() in PHP

I am a beginner programmer trying to insert the the now() value into my field date. I have achieved this before and copied the structure word by word but still does not work. I have also viewed other stackoverflow questions and I think that my database structure is correct. Here is INSERT php code:
try{
$conn = new mysqli("xxxxx", "xxxxx", "xxxxxxxx", "xxxxxxx");
$userid = $_GET['userid'];
$title = $_GET['title'];
$comment = $_GET['comment'];
$query = "INSERT into enquiries (userid, title, comment, Resolved, date)
values ('" . addslashes($userid) . "','" . addslashes($title) . "','" . addslashes($comment) . "', N, now() )";
$result = $conn->query($query);
if (!$result){
$json_out = "[" . json_encode(array("result"=>0)) . "]";
}
else {
$json_out = "[" . json_encode(array("result"=>1)) . "]";
}
echo $json_out;
$conn->close();
}
This set of codes worked and inserted values before I added now()
Here is my table structure:
Here is my other table structure that inserted now() just fine:
Your "Resolved" value needs to be in quotes, because you have it defined as a varchar. This would be the case for any of the "char" family of datatypes.
$query = "INSERT into enquiries (userid, title, comment, Resolved, date)
values ('" . addslashes($userid) . "','" . addslashes($title) . "','" . addslashes($comment) . "', 'N', now() )";
Hope this helps!
Sometimes database has some restrictions.. So try using like this NOW() than now() or else use CURDATE().

MySQL inserts values into wrong columns

Problem
With a php website, I have a form to collect information which will then be inserted into the MySQL database, but there are these three columns that have the wrong values inserted into them. The rest are all in the correct order.
Values inserted as php variables via MySQL transaction.
Thank you for your time.
phpmyadmin display (first row is manually corrected)
Code:
<?php
function registerPatient($ptUsername, $ptPassword, $ptFirstName, $ptLastName, $ptSalutation, $ptEmail, $ptDOB, $ptPostCode, $ptHouseNo, $ptTelNo, $link)
{
$accType = "Patient";
$dtID = $_COOKIE["ID"];
$errors = "";
$SQL_patientInsert =
"START TRANSACTION;
INSERT INTO accDetails (`username`, `hashPassword`, `accType`)
VALUES ('" . $ptUsername . "',
'" . $ptPassword . "',
'" . $accType . "');
INSERT INTO ptProfile (`firstName`, `lastName`, `salutation`, `email`, `DOB`, `postCode`, `houseNo`, `telephoneNo`, `dtID`, `ptID`)
VALUES ('" . $ptFirstName . "',
'" . $ptLastName . "',
'" . $ptSalutation . "',
'" . $ptEmail . "',
'" . $ptDOB . "',
'" . $ptPostCode . "',
'" . $ptHouseNo . "',
'" . $ptTelNo . "',
'" . $dtID . "',
LAST_INSERT_ID());
COMMIT;";
if (mysqli_multi_query($link, $SQL_patientInsert)) {
$errors .= "";
} else {
$errors .= "MYSQL Error: ". mysqli_error($link);
}
return $errors;
}
?>
Var_Dump of $SQL_patientInsert
string(495) "START TRANSACTION; INSERT INTO accDetails (`username`, `hashPassword`, `accType`) VALUES ('bingbong', '$2y$10$WDvSHSxzIxaYB8dPGLRIWOFyIdPXxSw5JDXagOxeYuJUtnvFhI.lO', 'Patient'); INSERT INTO ptProfile (`firstName`, `lastName`, `salutation`, `email`, `DOB`, `postCode`, `houseNo`, `telephoneNo`, `dtID`, `ptID`) VALUES ('Dr', 'Bing', 'Bong', 'EMAIL REMOVED FOR SO', '1996-08-02', 'POSTCODE REMOVED FOR SO', '7', '83824', '1256', LAST_INSERT_ID()); COMMIT;"
Table Structure
Table Structure in PHPMyAdmin, no autoincrements, all values allowed to be null
Your are calling your function with wrong parameters order.
Change this line ($ptFirstName <-> $ptSalutation);
function registerPatient($ptUsername, $ptPassword, $ptFirstName, $ptLastName, $ptSalutation, $ptEmail, $ptDOB, $ptPostCode, $ptHouseNo, $ptTelNo, $link)
with
function registerPatient($ptUsername, $ptPassword, $ptSalutation, $ptFirstName, $ptLastName, $ptEmail, $ptDOB, $ptPostCode, $ptHouseNo, $ptTelNo, $link)
I think you just mixed up your variables somewhere. Have you checked the form? Try printing out all the variables right before you build the query and check if they correspond correctly.

MySQL Insert statement not executing

I am trying to run an mySQL insert statement like so:
function insertAppointment($connection, $id, $firstname, $lastname, $email, $phone, $date, $time){
$sql = "INSERT INTO `appointments` (firstname, lastname, email, phone, app_date, app_time) VALUES ('" . $id . "', '" . $firstname . "', '" . $lastname . "', '" . $email . "', " . $date . ", " . $time . ")";
$connection->query($sql);
}
$connection is my connection string, which is not the problem. I am able to use it for select statement like so:
function getTakenDates($connection){
$query = mysqli_query($connection, "SELECT app_date, app_time FROM `appointments`");
$results = array();
while($row = mysqli_fetch_assoc($query)){
$results[] = $row;
}
return $results;
}
You are vulnerable to SQL injection attacks, and are creating an incorrect query with your $date/$time values:
INSERT .... VALUES (..., 2014-11-10, 14:58:00)
since your date value is unquoted, you'll actually be trying to insert the result of that math operation (remember - is SUBTRACTION if it's not in a string), and 14:58:00 is a totally invalid number - mysql has no idea what those : chars are.
You want
$sql = "[..snip..] "', '" . $date . "', '" . $time . "')";
^-------------^--^-------------^----
instead. note the extra quotes. That'll produce
INSERT .... VALUES (..., '2014-11-10', '14:58:00')

Error in Inserting Values into PostgreSQL table through php

I'm trying to insert received values into postgresql table using php. I can't figure out why this statement doesn't work
$query = "INSERT INTO user_info (name, emailAddress, phoneNumber, jobDesc) VALUES ('" . $name . "," . $emailAddr . "," . $phoneNumber . "," . $jobDesc ."')";
I get this error:
Query failed: ERROR: column "emailaddress" of relation "user_info" does not exist
However, I tried this one:
$query = "INSERT INTO user_info VALUES ('" . $name . "," . $emailAddr . "," . $phoneNumber . "," . $jobDesc ."')";
It works, but it inserts all values into first column!
I'm not sure what I'm missing here!
I think you are missing a whole host of single quotes in your VALUES list...
$query = "INSERT INTO user_info (name, emailAddress, phoneNumber, jobDesc) VALUES ('" . $name . "','" . $emailAddr . "','" . $phoneNumber . "','" . $jobDesc ."')";

MySQL syntax:You have an error in your SQL syntax…

I am receiving the following error from the code below.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#doe.com,username,5f4dcc3b5aa765d61d8327deb882cf99,09/05/2011 1:11:13 AM)' at line 1
$username = $_GET['username'];
$password = md5($_GET['password']);
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
$email = $_GET['email'];
$date = uk_date();
$conn = mysql_connect('localhost', 'myuser', 'mypass');
mysql_select_db('dbname');
$query = "INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES (". $firstname . ",". $lastname ."," . $email . "," . $username . "," . $password . "," . $date . ")";
$result = mysql_query($query) or die(mysql_error());
echo 'Success';
mysql_close($result);
Please could you let me know what my problem is? I am new to MySQL and PHP so please can you provide an explanation to what I have done wrong for later reference.
You haven't quoted any of the values in your INSERT, you should be saying something more like this:
$query = "INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES ('". $firstname . "','". $lastname ."','" . $email . "','" . $username . "','" . $password . "','" . $date . "')";
You should also be using mysql_real_escape_string on all those variables to make sure that any embedded quotes and such are properly encoded.
A better version would be something like this:
$query = sprintf("INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname),
mysql_real_escape_string($email),
mysql_real_escape_string($username),
mysql_real_escape_string($password),
mysql_real_escape_string($date));
You should also listen to BoltClock and use PDO and placeholders so you don't have to worry about your quotes and escaping so much. PDO will also make it easier to switch databases.
Probably user input have a single quote character, so it will be safe to escape special character before send it as query to database, this will prevent your script from sql injection.
$query = "INSERT INTO accounts (FirstName, LastName, Email, Username, Password, LastLoginDate) VALUES ('$firstname', '$lastname', '$email','$username','$password', '$date')";
Once you have escaped your variables like suggested by other, you need to surround them with quotes if they are string varialbles :
mysql_select_db('dbname');
$query = "INSERT INTO accounts
(FirstName, LastName, Email, Username, Password, LastLoginDate)
VALUES ('". $firstname . "','". $lastname ."','" . $email . "','" .
$username . "','" . $password . "','" . $date . "')";
$result = mysql_query($query) or die(mysql_error());
echo 'Success'; mysql_close($result);
In this case i added single quotes. you shouldnt have any errors now

Categories