Why doesn't my SQL insert into work? - php

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()

Related

MySQL query is incorrect

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

Prepare() Statement isn't working PHP (SQL Query)

I'm working into a Php Script to create fields in an online database, and the prepare() statement isn't working so I think I might fail in the query as I'm not good using SQL, here is the function;
function createQuestion($CAT, $PREG, $RESP1, $RESP2, $RESP3, $RESPC) {
$sql = "INSERT INTO `table1` (`ID`, `CAT`, `PREG`, `RESP1`, `RESP2`, `RESP3`, `RESPC`) VALUES (NULL, ?, ? , ?, ?, '?, ?)";
if ($stmt = $this->con->prepare($sql)) {
echo "prepare works okay!";
$stmt->bind_param("isssss", $CAT, $PREG, $RESP1, $RESP2, $RESP3, $RESPC);
if ($stmt->execute()) {
return true;
} else{
return false;
}
} else {
echo "prepare isn't working."
}
}
Apart from others errors specified in other classes, I'm getting the "prepare isn't working."
Your statement has a typo in it:
INSERT INTO `table1` (`ID`, `CAT`, `PREG`, `RESP1`, `RESP2`, `RESP3`, `RESPC`) VALUES (NULL, ?, ? , ?, ?, '?, ?);
Note the single ' mark in the VALUES(...) section? Try this instead:
INSERT INTO `table1` (`ID`, `CAT`, `PREG`, `RESP1`, `RESP2`, `RESP3`, `RESPC`) VALUES (NULL, ?, ?, ?, ?, ?, ?);

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).

How to execute multiply queries using PHP's prepared statemens with MySQL's transaction?

I need to execute 2 or more not identical queries (INSERT's in this example.) using PHP's prepared statements and MySQL's transactions. So if I have a 2 INSERT statements, I want both of them executed, or none of them.
I want to traslate this example MySQL transaction to a PHP code:
START TRANSACTION;
INSERT INTO `file` (`name`, `mime_type`, `size`, `comment`) VALUES ('file.png', 'image/png', '1024', 'My comment');
INSERT INTO `complementary_file` (`file_id`, `user_id`) VALUES (LAST_INSERT_ID(), '1');
COMMIT;
PHP code I'm working on:
mysqli_autocommit($connection, FALSE);
if ($stmtFile = mysqli_prepare($connection, "INSERT INTO `file` (`name`, `mime_type`, `size`, `comment`) VALUES (?, ?, ?, ?)")) {
mysqli_stmt_bind_param($stmtFile, 'ssis', $name, $mime_type, $size, $comment);
if (mysqli_stmt_execute($stmtFile)) {
if ($stmtComplementaryFile = mysqli_prepare($connection, "INSERT INTO `complementary_file` (`file_id`, `user_id`) VALUES (?, ?)")) {
mysqli_stmt_bind_param($stmtComplementaryFile, 'ii', mysqli_insert_id($connection), $user_id);
mysqli_stmt_execute($stmtComplementaryFile);
}
} else {
mysqli_rollback($connection);
}
}
mysqli_commit($connection);
PHP code above works but what if I have more critical statements to execute? Is there are good way to execute statements with PHP's prepared statemens and transactions at the same time?
Please note that for $stmtComplementaryFile I must have a mysqli_insert_id() value. Also please note that I am not using PDO with this code — I appreciate if suggestions will be MySQLi. Thanks.
The following SQL:
START TRANSACTION;
INSERT INTO `file` (`name`, `mime_type`, `size`, `comment`) VALUES ('file.png', 'image/png', '1024', 'My comment');
INSERT INTO `complementary_file` (`file_id`, `user_id`) VALUES (LAST_INSERT_ID(), '1');
COMMIT;
Can be converted to PHP (with prepared statements) as follows:
mysqli_begin_transaction($connection, MYSQLI_TRANS_START_READ_WRITE);
if ($stmtFile = mysqli_prepare($connection, "INSERT INTO `file` (`name`, `mime_type`, `size`, `comment`) VALUES (?, ?, ?, ?)")) {
mysqli_stmt_bind_param($stmtFile, 'ssis', $name, $mime_type, $size, $comment);
if (mysqli_stmt_execute($stmtFile)) {
if ($stmtComplementaryFile = mysqli_prepare($connection, "INSERT INTO `complementary_file` (`file_id`, `user_id`) VALUES (?, ?)")) {
mysqli_stmt_bind_param($stmtComplementaryFile, 'ii', mysqli_insert_id($connection), $user_id);
mysqli_stmt_execute($stmtComplementaryFile);
}
} else {
mysqli_rollback($connection);
}
}
mysqli_commit($connection);
In general these two statements are equivalent, however it's a good idea to know what transactions are and what transactions are not.
Transactions are a mechanism to ensure that bulk operations are executed atomically and their results are reflected in the database only if ALL of them succeed. It ensures atomicity of operations.
Transactions are not a mechanism to implement a mutual exclusion lock on the tables. If a table needs to be locked then the LOCK TABLES [READ|WRITE] needs to be used. Equivalently in PHP this is achieved by doing a:
mysqli_query($connection, "LOCK TABLES tableName as TableAlias [read|write]");
followed by
mysqli_query($connection, "UNLOCK TABLES");

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