MySQL query is incorrect - php

I have no clue why the following MySQL Query keeps failing. It tells me it has invalid syntax. It always says it at the em-mail area of the code, but there is no obvious errors. I am cleaning up the strings before passing them into the MySQL query
$query = "INSERT INTO `ToReview` (`number`, `role`, `name`, `email`, `dob`,
`englishskills`, `previousmember`, `reasonYes`, `whyjoin`,
`whatcouldyoubring`, `roleplayexperience`, `roleplayexperiencedetail`,
`commit`, `minimumperiod`) VALUES (NULL, ".$role.", ".$name.", ".$email.",
".$dob.", ".$englishskills.", ".$previousmember.", ".$reasonYes.",
".$whyjoin.", ".$whatcouldyoubring.", ".$roleplayexperience.",
".$roleplayexperiencedetail.", ".$commit.", ".$minimumperiod.");";
$result = mysqli_query($con, $query) or die(mysqli_error($con));

you are closing double quotes at the ending semicolon, remove that and try again
$query = "INSERT INTO `ToReview` (`number`, `role`, `name`, `email`, `dob`,
`englishskills`, `previousmember`, `reasonYes`, `whyjoin`,
`whatcouldyoubring`, `roleplayexperience`, `roleplayexperiencedetail`,
`commit`, `minimumperiod`) VALUES (NULL, '$role', '$name', '$email',
'$dob','$englishskills', '$previousmember', '$reasonYes',
'$whyjoin', '$whatcouldyoubring', '$roleplayexperience',
'$roleplayexperiencedetail', '$commit', '$minimumperiod')";

Your query doesn't put any single-quotes around each value in the VALUES clause. Unless they're all numeric values or NULL, this will result in invalid SQL.
You can see it if you echo $query before you use it:
INSERT INTO `ToReview` (`number`, `role`, `name`, `email`, `dob`,
`englishskills`, `previousmember`, `reasonYes`, `whyjoin`,
`whatcouldyoubring`, `roleplayexperience`, `roleplayexperiencedetail`,
`commit`, `minimumperiod`) VALUES (NULL, myrole, myname, my#email.com,
2014-02-03, excellent, no, myreason,
myreason, cookies, lots,
lots and lots, yes, 1 month);
Each string or date value in your INSERT statement needs single-quotes.
You could fix this by writing the code like this:
$query = "INSERT INTO `ToReview` (`number`, `role`, `name`, `email`, `dob`,
`englishskills`, `previousmember`, `reasonYes`, `whyjoin`,
`whatcouldyoubring`, `roleplayexperience`, `roleplayexperiencedetail`,
`commit`, `minimumperiod`) VALUES (NULL, '".$role."', '".$name."', '".$email."',
'".$dob.", '".$englishskills."', '".$previousmember."', '".$reasonYes."',
'".$whyjoin."', '".$whatcouldyoubring."', '".$roleplayexperience."',
'".$roleplayexperiencedetail."', '".$commit."', '".$minimumperiod."');";
Except I made a mistake and forgot one of the single-quotes. Can you spot it?
It would be much easier if you use prepared queries with parameters, and stop copying variables into SQL strings. It makes it way easier to write dynamic SQL like this, without tearing out your hair trying to find
$query = "INSERT INTO `ToReview` (`number`, `role`, `name`, `email`, `dob`,
`englishskills`, `previousmember`, `reasonYes`, `whyjoin`,
`whatcouldyoubring`, `roleplayexperience`, `roleplayexperiencedetail`,
`commit`, `minimumperiod`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
It a prepared statement, the ? don't need any quotes. In fact you must not put quotes around each ? because that would make it a literal '?' instead of a placeholder.
Then you prepare the query, bind variables into it.
$stmt = mysqli_prepare($con, $query) or die(mysqli_error($con));
mysqli_stmt_bind_param($stmt, 'sssssssssssss', $role, $name, $email,
$dob, $englishskills, $previousmember, $reasonYes,
$whyjoin, $whatcouldyoubring, $roleplayexperience,
$roleplayexperiencedetail, $commit, $minimumperiod);
You need the same number of variables as placeholders, and you bind them in the same order they appear in your query. Mysqli also requires a string like 'sss...' where each letter in that string corresponds to one of your parameters, and 's' means the parameter is a string, 'i' means it's an integer, etc.
Once you have prepared and bound parameters, just execute the prepared statement and get the results:
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
This way you don't give yourself eyestrain trying to match all the different types of quotes.
Another tip: PDO makes this even easier! You can bind and execute in one step, just by passing an array to the execute function.
$stmt = $pdo->prepare($query);
$stmt->execute([$role, $name, $email,
$dob, $englishskills, $previousmember, $reasonYes,
$whyjoin, $whatcouldyoubring, $roleplayexperience,
$roleplayexperiencedetail, $commit, $minimumperiod]);
$results = $stmt->fetchAll();

Strings like $name need to be enclosed using '.
$query = "INSERT INTO `ToReview` (`number`, `role`, `name`, `email`, `dob`,
`englishskills`, `previousmember`, `reasonYes`, `whyjoin`,
`whatcouldyoubring`, `roleplayexperience`, `roleplayexperiencedetail`,
`commit`, `minimumperiod`) VALUES (NULL, ".$role.", '".$name."', '".$email."',
'".$dob."', ".$englishskills.", ".$previousmember.", '".$reasonYes."',
'".$whyjoin."', '".$whatcouldyoubring."', '".$roleplayexperience."',
'".$roleplayexperiencedetail."', '".$commit."', '".$minimumperiod."');";
Or you could use prepared statements

Related

insert data by GET

I want insert data by GET in my sql but I can not insert data
<?php
include("config.php");
$f=$_GET["first_name"];
$l=$_GET["last_name"];
$e=$_GET["email"];
$m=$_GET["mobile"];
$b=$_GET["birthday"];
$g=$_GET["gender"];
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES ('$f', '$l', '$e', '$m', '$b', '$g')";
mysqli_query($insert);
?>
I try insert data by this link :
http://localhost:8888/restfull/insert.php?f=hayoo
It's been a long time since I have used mysqli the code below should most likely run though. As others have mentioned never bind unsanitized data (Even if you think you trust the data it's safe to use prepared statements still).
<?php
//Create you db connection
$conn = new mysqli('server', 'user', 'password', 'databasename');
//Create insert statement. Never concat un-sanitized data in statements
$insert="INSERT INTO user ( `first_name`, `last_name`, `email`, `mobile`, `birthday`, `gender`)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
//Values corespond to ? except the first param which represents format of expected data. "s" stands for string
$stmt->bind_param(
'ssssss',
$_GET["first_name"],
$_GET["last_name"],
$_GET["email"],
$_GET["mobile"],
$_GET["birthday"],
$_GET["gender"]
);
$stmt->execute();
Your url would look like this:
http://localhost:8888/restfull/insert.php?first_name=john&last_name=Doe&email=test#test.com&mobile=0&birthday=May&gender=male
Make sure if you are putting the url above in some type of form you correctly url encode values (I notice many of the values you are collecting will like require it slashes etc).

MySQL more columns then in php query

I changed to another database with more columns. Nut now my register page doesn't work anymore. The tables all have default settings.
How can I let the query put all the data in the columns and use the defaults for other columns?
This is my query:
mysql_query("
INSERT INTO `users`
(`username`, `password`, `mail`, 'account_created', 'ip_last', 'ip_reg')
VALUES(
'".$naam."', '".$wachtwoord."', '".$email."',
'".$timestamp."', '".$ip."', '".$ip."'
)
");
It worked before, but now on this new database it doesn't work anymore. I didn't change my php version or something.
You can use variables in query strings without quotes.
By the way you should think about more secure -
PDO? What is this magic system
PDO Version:
$query = $db->prepare("INSERT INTO users(username, password, mail, account_created, ip_last, ip_reg) VALUES (?, ?, ?, ?, ?, ?)");
$query->execute(array($naam, $wachtwoord, $email, $timestamp, $ip, $ip));
Trash Version:
mysql_query("INSERT INTO users(username, password, mail, account_created, ip_last, ip_reg) VALUES ($naam, $wachtwoord, $email, $timestamp, $ip, $ip)");
Know the difference between back ticks and single quotes
mysql_query("
INSERT INTO `users` (`username`, `password`, `mail`, `account_created`, `ip_last`, `ip_reg`) VALUES('".$naam."', '".$wachtwoord."', '".$email."', '".$timestamp."', '".$ip."', '".$ip."')");

Why doesn't my SQL insert into work?

I know questions like this exist all over, but I can't see what's wrong with my code. The DB works and I run an update query just fine earlier on in the code.
Query 1:
mysql_query("INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES ('".$login."', '".$ip."', '".$details->hostname."', '".$loc."', 'success', NOW()");
Query 2:
mysql_query("INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES ('".$login."', '".$ip."', '".$details->hostname."', '".$loc."', 'failure', NOW()");
Here is an echo of the string as requested:
INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES ('AAL', '**.60.**.**', 'c-174-**-**-**.hsd1.**.comcast.net', 'Town, US', 'success', NOW()
Looks like you are missing the final closing ). Also use prepared statements. Much cleaner and safer. Here is a quick example of what a Prepared Statement would look like (adapted from here) (you wold also need to make other changes to your PHP script to start using them)
$stmt = $mysqli->prepare("INSERT INTO `login_history` (`memberid`, `ip`, `host`, `location`, `status`, `date`) VALUES (?, ?, ?, ?, ?, NOW())")
$stmt->bind_param('sssss', $login, $ip, $details->hostname, $loc, 'failure');
$stmt->execute()

Is it possible to combine mysqli prepared statement with multiple inserts?

I am well-versed in the old php mysql extension.
I am working on my first script that uses the mysqli extension.
I am going to be inserting a large number of rows into a table that are being generated dynamically.
Is it possible to use a prepared statement to insert multiple rows into a table without previously knowing the number of new rows that will be inserted each time?
$stmt = $mysqli->prepare("INSERT INTO `activity` (`id`, `name`, `type`) VALUES ?, ?, ?;");
If that isn't possible, which would be more efficient:
prepared statement, one row at a time
non-prepared statement, ~50 rows at a time
// prepared statement
$stmt = $mysqli->prepare("INSERT INTO `activity` (`id`, `name`, `type`) VALUES (?, ?, ?)");
for($i=0;$i<$limit;$i++)
{
$stmt->bind_param('iss', $id[$i], $name[$i], $type[$i]);
$stmt->execute();
}
// non-prepared statement
$query = "INSERT INTO `activity` (`id`, `name`, `type`) VALUES ";
for($i=0;$i<$limit;$i++)
{
$query .= "\n(".$mysqli->real_escape_string($id[$i]), $mysqli->real_escape_string($name[$i]), $mysqli->real_escape_string($type[$i])."),";
}
$query = substr($query, 0, -1).';';
PHP v.5.3.8
MySQL v. 5.1.60
$stmt = $mysqli->stmt_init();
if($stmt->prepare("INSERT INTO `activity` (`id`, `name`, `type`) VALUES (?, ?, ?)"))
{
$stmt->bind_param('iss', $_id, $_name, $_type);
for($i=0;$i<$limit;$i++)
{
$_id = $id[$i];
$_name = $name[$i];
$_type = $type[$i];
$stmt->execute();
}
}
should do it for you!

php prepared statement fails.

I'm guessing I'm missing something, but I can't seem to get this statement to work. When I load it into the page I get the white screen of death.
Here is what I'm trying to get to run
$statement = $db-> prepare("INSERT INTO `simplyaccomplished`.`blog_comment` (`ID`, `comment`, `date`, `ip_address`, `valid`, `name`, `blogcomment_ID`) VALUES (NULL, ?, NOW(), ?, 0, ?, ? );");
$statement -> bind_param("sssi",$comment, $ipaddress, $name , $comment_id);
$statement -> execute($statement);
$statement -> close();
The weird thing is this runs perfectly
$query = ("INSERT INTO `simplyaccomplished`.`blog_comment` (`ID`, `comment`, `date`, `ip_address`, `valid`, `name`, `blogcomment_ID`) VALUES (NULL,'$comment' , NOW(), '$ipaddress', '0', '$name', '$comment_id');");
$result =$db->query($query);
If someone could tell me where I'm going wrong I would greatly appreciate it!
The PDO method you're looking for is named bindParam, not bind_param :)
Try mysqli method,
$statement = $db-> prepare("INSERT INTO `simplyaccomplished`.`blog_comment` (`ID`,
`comment`, `date`, `ip_address`, `valid`, `name`, `blogcomment_ID`)
VALUES (?, ?, ?, ?,?, ?, ?)");
$statement -> bind_param("ssssisi",
null,$comment,NOW(),$ipaddress, 0,$name , $comment_id);
Take a look at PDO and MySqlI.

Categories