I'm trying to insert some values into a database, however, it's always unsuccessful and I'm not sure what the problem is. Could I get some assistance please
$query1 = "INSERT INTO `incidenceoffire`(`locationOfFire`, `dateFireOccurred`, `timeFireOccurred`, `classOfFire`, `originOfFire`, `noOfWounded`,
`noOfFatalities`,`occupancy`,`noOfFirePersonnelOnScene`,`noOfFireTrucks`,`backupUsed`)
VALUES('$locationoffire', '$datefireoccurred', '$timefireoccurred', '$classoffire', '$originoffire', '$occupancy', '$noofwounded', '$nooffatalities',
'$noofpersonnel', '$nooftrucks', '$backuptrucks')";
$incidenceoffire_id = mysql_insert_id();
$query2 = "INSERT INTO `backuptrucks` (`unitName`) VALUES ('$unitname')";
$query2 .=" WHERE `IncidenceOfFire_incidentID` = '".$incidenceoffire_id."'";
$result = false;
if(mysql_query('BEGIN')){
if(mysql_query($query1) && mysql_query($query2))
{
$result = mysql_query('COMMIT');
echo '<script type="text/javascript">
alert("Insert Successful!");
</script>';
}
else
{
mysql_query('ROLLBACK');
echo '<script type="text/javascript">
alert("Insert Unsuccessful!");
</script>';
}
}
For the purpose of clarity, here's what you need. I'm not going to optimize it or anything but it's a baseline for where you should start.
$mysqli = new mysqli('host', 'name', 'user', 'database');
$query1 = $mysqli->prepare('INSERT INTO
`incidenceoffire`(
`locationOfFire`,
`dateFireOccurred`,
`timeFireOccurred`,
`classOfFire`,
`originOfFire`,
`noOfWounded`,
`noOfFatalities`,
`occupancy`,
`noOfFirePersonnelOnScene`,
`noOfFireTrucks`,
`backupUsed`
)
VALUES(?,?,?,?,?,?,?,?,?,?,?));
In the above we're using mysqli's prepare. This function will allow us to safely escape the data that is being passed into the query. This is for security purposes. the ? represents the value that we're inserting associated with the field's we've identified above.
$query1->bind_param('sssssssssss',
$locationoffire,
$datefireoccurred,
$timefireoccurred,
$classoffire,
$originoffire,
$occupancy,
$noofwounded,
$nooffatalities,
$noofpersonnel,
$nooftrucks,
$backuptrucks);
Here, we've used bind_param to bind the variable to the ?'s that we've used in the prepared statement. This allows us to safely escape the data. the s in the first argument stands for string as the data we expect to receive from that variable should be a string. You can also use i for integer - when expecting only numbers, and d for double, if you expect to have .'s and ,'s. Lastly, you can use b if you expect a blob to be transferred over time to the statement.
Now, because you have two statements, repeat the above and use $query2, then you can perform your conditional. We will use execute() to execute the prepared statement we built earlier.
if($query1->execute() && $query2->execute()):
$result[] = $query1->commit();
$result[] = $query2->commit();
echo '<script type="text/javascript">alert("Insert Successful!");</script>';
else:
$result[] = $query1->rollback();
$result[] = $query2->rollback();
echo '<script type="text/javascript">alert("Insert Unsuccessful!");</script>';
endif;
This should all function for you from the get go, but please read and understand what's being relayed. Always use documentation and examples provided at http://php.net, and please follow best practices for security less you create a site that becomes hacked and I end up repairing it one day
Related
I have a MySQL statement that won't work for me. I've checked several parts of the code but it keeps returning null as the result. I've also tried replacing the WHERE enc_mail = AND enc_public_id=" to "WHERE 1" to check if it was a problem with the variables, but it is not. I did not get errors either.
$connect_db = mysqli_connect("myhost","my username","my password","my db");
$mail_id = crypto(mysqli_real_escape_string($connect_db,htmlspecialchars($_GET['em'])),'e');
$public_id = mysqli_real_escape_string($connect_db,htmlspecialchars($_GET['public']));
$active_true = true;
$check = $connect_db->prepare("SELECT active FROM enc_data WHERE enc_mail=? AND enc_pub_id=?");
$check->bind_param("ss", $mail_id, $public_id);
$active = $check->execute();
if($active[0]=="" ){
//It goes here once the code is run
}
You need to apply bind_result and then fetch
Also there is absolutely no reason to escape_string when using prepared statements as #GrumpyCrouton said
i would recommend you switch to PDO as it is more straightforward
I agree with #Akintunde that you should NOT use escaping and htmlspecialchars on query parameters. Escaping is redundant when you use query parameters. htmlspecialchars is just when you output content to HTML, not for input to SQL.
You don't necessarily have to use bind_result() for a mysqli query. You can get a result object from the prepared statement, and then use fetch methods on the result object to get successive rows.
Here's how I would write your code:
// makes mysqli throw exceptions if errors occur
mysqli_report(MYSQLI_REPORT_STRICT);
$connect_db = new mysqli("myhost", "my username", "my password", "my db");
$mail_id = $_GET['em'];
$public_id = $_GET['public'];
$active_true = true;
$sql = "SELECT active FROM enc_data WHERE enc_mail=? AND enc_pub_id=?";
$stmt = $connect_db->prepare($sql);
$stmt->bind_param("ss", $mail_id, $public_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
if($row["active"]=="" ){
//It goes here once the code is run
}
}
But in fact I would prefer to use PDO instead of mysqli, so I guess that's not really how I would write the OP's code. :-)
So I'm making my own blog scripts using MYSQL and PHP.
I had the whole 'writing the blog to a database' thing working perfectly, until I realised that if you tried to write a blog with speech marks, this would prevent the INSERT statement from working (obviously - the speechmarks were ending the SQL statement).
So I tried to use real_escape_string, and now the INSERT doesn't work even if you exclude quotes.
I tried using:
sqlstate
in order to find out the issue, and it returned "42000" - which, after googling for a little bit, refers to a syntax error, which doesn't make much sense as there is no syntax error before the use of real_escape_string.
Also, I'm now getting this error:
Call to a member function close() on a non-object in /postarticle.php on line 37
Which refers to the close() call in the ELSE statement.
Please may you help? Been going round in circles for a while. Here is my code:
<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'CENSORED';
$connection = new mysqli($host,$user,$pass,$db);
$_SESSION["article"] = $_POST["article"];
$date_of_blog = getdate();
$article = ($_SESSION["article"]);
$sql1 = "SELECT * FROM `Blogs`";
$res1 = $connection->query($sql1);
$newrows = $res1->num_rows + 1;
$sql2 = "INSERT INTO Blogs(BlogID, Blog_Contents, D_O_B) VALUES ('$newrows','$article','$date_of_blog')";
$sql2 = $connection->real_escape_string($sql2);
$res2 = $connection->query($sql2);
if ($res2->num_rows == $newrows)
{
$res->close();
$connection->close();
header( 'Location: adminpanel.php' );
}
else
{
echo ($connection->sqlstate);
$connection->close();
$res->close();
}
exit();
?>
Also, on a side note, the getdate() call that I've got has never worked. In the database every blog post comes up as:
0000:00:00 00:00:00
EDIT:
Issue is now solved. Find the functional code below:
<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'CENSORED';
$connection = new mysqli($host,$user,$pass,$db);
$_SESSION["article"] = $_POST["article"];
$article = ($_SESSION["article"]);
$article = $connection->real_escape_string($article);
$sql1 = "SELECT * FROM `Blogs`";
$res1 = $connection->query($sql1);
$newrows = $res1->num_rows + 1;
$sql2 = "INSERT INTO Blogs(BlogID, Blog_Contents, D_O_B) VALUES (\"$newrows\",\"$article\",CURDATE())";
$res2 = $connection->query($sql2);
if ($res2 != false)
{
header( 'Location: adminpanel.php' );
}
else
{
echo ($connection->sqlstate);
}
$connection->close();
$res->close();
exit();
?>
I'm very sorry if these questions are basic and annoy the professionals around here; I've tried to follow the guidelines and I've googled for a while etc. I just haven't found any solutions that match my issue(s).
Thankyou for your time.
There are a number issues with the code as originally posted. Chiefly, the cause of the two issues you initially identified is a misuse of mysqli::real_escape_string(). It needs to be called on each variable individually which appears in the code. So instead of calling it on the whole statement, it must be called multiple times for multiple variables like:
$article = $connection->real_escape_string($connection);
The failure of the query due to incorrect quoting (due to real_escape_string()) is the reason for the error message calling close().
As ascertained in the comments, you are using num_rows + 1 to validate that one new row has been inserted based on the previous number of rows returned. This is problematic for a few reasons. Mainly, it exposes a race condition wherein a row may be inserted from two sessions at once and one or both will fail because the expected value for $newrows doesn't match. Really BlogID should be an auto_increment column in your database. That eliminates the need for any logic around it whatsoever. You don't even need to include it in the INSERT because it will be automatically incremented.
That also completely eliminates the need for the first SELECT statement.
Substituting MySQL's native NOW() function for the date value, you can simplify the statement to:
INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES ('$article', NOW())
To test success or failure of the insert, you just need to verify that its variable is not false.
Putting this together, your code can be reduced as:
if (!isset($_POST['article'])) {
// exit or handle an empty post somehow...
}
$connection = new mysqli($host,$user,$pass,$db);
$_SESSION["article"] = $_POST["article"];
// Escape $article for later use
$article = $connection->real_escape_string($_SESSION["article"]);
// Only an INSERT is needed. $article is already escaped
$sql = "INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES ('$article', NOW())";
// Run the query
$res = $connection->query($sql);
// Test for failure by checking for a false value
if ($res) {
// The connection & resource closure can be omitted
// PHP will handle that automatically and implicitly.
header( 'Location: adminpanel.php' );
// Explictly exit as good practice after redirection
exit();
}
else {
// The INSERT failed. Check the error message
echo $connection->error;
}
This should bring your current code into working order. However, since you're learning this it is an excellent time to begin learning to use prepared statements via prepare()/bind_param()/execute() in MySQLi. This is a recommended best practice to prevent SQL injection, although using real_escape_string() works as long as you use it correctly and never forget.
See How can I prevent SQL injection in PHP for examples.
But it would look like:
// connection already established, etc...
// Prepare the statement using a ? placeholder for article
$stmt = $connection->prepare("INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES (?, NOW())");
if ($stmt) {
// bind in the variable and execute
// Note that real_escape_string() is not needed when using
// the ? placeholder for article
$stmt->bind_param('s', $_SESSION['article']);
$stmt->execute();
// Redirect
header( 'Location: adminpanel.php' );
exit();
}
else {
echo $connection->error;
}
You need to apply the real_escape_string function to the variables not the entire SQL string.
$sql2 = "INSERT INTO Blogs(BlogID, Blog_Contents, D_O_B) VALUES ('".$connection->real_escape_string($newrows)."','".$connection->real_escape_string($article)."','".$connection->real_escape_string($date_of_blog)."')";
The purpose is to remove anything that might be misinterpreted as query functions by MySQL, but there are parts of the query that you obviously want to be interpreted as such.
Here's the problematic PHP function:
//Get data associated with $criteria from db
function getUserData($criteria, $value) {
//obtain user data from db based on $criteria=$value
global $pdo;
//echo $criteria . " " . $value;
try {
$sql = 'SELECT id, first, last, email, userid FROM users WHERE :criteria= :value';
//var_dump($sql);
$st = $pdo->prepare($sql);
$st->bindValue(':criteria', $criteria);
$st->bindValue(':value', $value);
$st->execute();
}
catch (PDOException $ex) {
$error = "Failed to obtain user data.";
$errorDetails = $ex->getMessage();
include 'error.html.php';
exit();
}
$row = $st->fetch();
//var_dump($row);
if ($row)
{
$userdata = array();
$userdata['id'] = $row['id'];
$userdata['first'] = $row['first'];
$userdata['last'] = $row['last'];
$userdata['email'] = $row['email'];
$userdata['userid'] = $row['userid'];
return $userdata;
}
return FALSE;
}
I use this function to return a whole row of data associated with specific column in it.
When used at it's current state, with a call like that getUserData("email", "John_Stewart_2013"), it returns false, meaning an empty result, while the same query runs fine in MySQL CLI.
If I, on the other hand, substitute the query string $sql with :
$sql = "SELECT id, first, last, email, userid FROM users WHERE $criteria='$value'";
And comment out the bindValue calls, Every thing runs fine in PHP, and the query returns as desired.
But the problem is, those function arguments are user-submitted form data, meaning the solution is vulnerable to SQL Injection.
What's wrong here in the first query form?
You can't use bindValue with column names I'm afraid.
If you think about what a prepared statement is, this should become more obvious. Basically, when you prepare a statement with the database server, it creates an execution plan for the query beforehand, rather than generating it at the time of running the query. This makes it not only faster but more secure, as it knows where it's going, and the datatypes that it will be using and which are going to be input.
If the column/table names were bindable in any way, it would not be able to generate this execution plan, making the whole prepared statement idea somewhat redundant.
The best way would be to use a hybrid query like so:
$sql = "SELECT id, first, last, email, userid FROM users WHERE $criteria = :value";
I'm going to hope that the $criteria column isn't entirely free form from the client anyway. If it is, you'd be best limiting it to a specific set of allowed options. A simplistic way to do would be to build an array of allowed columns, and check if it's valid with in_array, like so:
$allowed_columns = array('email', 'telephone', 'somethingelse');
if (!in_array($criteria, $allowed_columns))
{
$error = "The column name passed was not allowed.";
$errorDetails = $ex->getMessage();
include 'error.html.php';
exit;
}
I have a a php page which updates a mySql database it works fine on my mac (localhost using mamp)
I made a check if its the connection but it appears to be that there is a connection
<?php require_once('connection.php'); ?>
<?php
$id = $_GET['id'];
$collumn = $_GET['collumn'];
$val = $_GET['val'];
// checking if there is a connection
if(!$connection){
echo "connectioned failed";
}
?>
<?php
$sqlUpdate = 'UPDATE plProducts.allPens SET '. "{$collumn}".' = '."'{$val}'".' WHERE allPens.prodId = '."'{$id}'".' LIMIT 1';
mysql_query($sqlUpdate);
// testing for errors
if ($sqlUpdate === false) {
// Checked this and echos NO errors.
echo "Query failed: " . mysql_error();
}
if (mysql_affected_rows() == 1) {
echo "updated";
} else {
echo "failed";
}?>
In the URL i pass in parameters and it looks like this: http://pathToSite.com/updateDB.php?id=17&collumn=prodid&val=4
Maybe this has to do with the hosting? isn' t this simple PHP mySql database updating? what can be wrong here?
Why on localhost it does work?
Why on live server it doesn't?
Let's start with troubleshooting your exact problem. Your query is failing for some reason. We can find out what that problem is by checking what comes back from mysql_query, and if it's boolean false, asking mysql_error what went wrong:
$sh = mysql_query($sqlUpdate);
if($sh === false) {
echo "Query failed: " . mysql_error();
exit;
}
You have other problems here. The largest is that your code suffers from an SQL Injection vulnerability. Let's say your script is called foo.php. If I request:
foo.php?collumn=prodId = NULL --
then your SQL will come out looking like:
UPDATE plProducts.allPens SET prodId = NULL -- = "" WHERE allPens.prodId = "" LIMIT 1
-- is an SQL comment.
I just managed to nuke all of the product IDs in your table.
The most effective way to stop SQL injection is to use prepared statements and placeholders. The "mysql" extension in PHP doesn't support them, so you'd also need to switch to either the must better mysqli extension, or the PDO extension.
Let's use a PDO prepared statement to make your query safe.
// Placeholders only work for *data*. We'll need to validate
// the column name another way. A list of columns that can be
// updated is very safe.
$safe_columns = array('a', 'b', 'c', 'd');
if(!in_array($collumn, $safe_columns))
die "Invalid column";
// Those question marks are the placeholders.
$sqlUpdate = "UPDATE plProducts.allPens SET $column = ? WHERE allPens.prodId = ? LIMIT 1";
$sh = $db->prepare($sqlUpdate);
// The entries in the array you pass to execute() are substituted
// into the query, replacing the placeholders.
$success = $sh->execute(array( $val, $id ));
// If PDO is configured to use warnings instead of exceptions, this will work.
// Otherwise, you'll need to worry about handling the exception...
if(!$success)
die "Oh no, it failed! MySQL says: " . join(' ', $db->errorInfo());
Most mysql functions return FALSE if they encounter an error. You should check for error conditions and if one occurs, output the error message. That will give you a better idea of where the problem occurred and what the nature of the problem is.
It's amazing how many programmers never check for error states, despite many examples in the PHP docs.
$link = mysql_connect(...);
if ($link === false) {
die(mysql_error());
}
$selected = mysql_select_db(...);
if ($selected === false) {
die(mysql_error());
}
$result = mysql_query(...);
if ($result === false) {
die(mysql_error());
}
Your call to mysql_query() is faulty; you're checking the contents of the variable you're passing in but the function call doesn't work that way. It returns a value which is what you should check. If the query failed, it returned false. If it returns data (like from a SELECT) it returns a resource handle. If it succeeds but doesn't return data (like from an INSERT) it returns true.
You also have some problems constructing your SQL. #Charles mentions SQL injection and suggests prepared statements. If you still want to construct a query string, then you need to use mysql_real_escape_string(). (But I would recommend you read up on the mysqli extension and use those functions instead.)
Secondly, you're concatenating strings with embedded substitution. This is silly. Do it this way instead:
$sqlUpdate = 'UPDATE plProducts.allPens SET '.$collumn.' = \''.$val.'\'
WHERE allPens.prodId = '.intval($id).' LIMIT 1';
If you must accept it in the querystring, you should also check that $collumn is set to a valid value before you use it. And emit and error page if it's not. Likewise, check that $id will turn into a number (use is_numeric()). All this is called defensive programming.
I am trying to insert values in database and values are not being inserted, here is the code i have:
$user_name = "username";
$password = "password";
$database = "database";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = 'INSERT INTO table (anInt, DomainName, URL, Rank, PageRank, Google, Bing, Boss, IndexedPage, Backlinks) VALUES ($anInt, $Domain, $URL, $Rank, $Pagerank, $Google, $Bing, $Yahoo, $Pages, $backlinks)';
$result = mysql_query($SQL);
mysql_close($db_handle);
print "Records added to the database";
it is printing that records added to the database but when looking at the database nothing is being added. some of the values are doubles, text, and ints. Is there anyway to debug this? I will be adding more information to the post if someone asks me to.
and of course I have an else statement i just thought it is not relevant since it is telling me that records are added.
First of all, you should escape the string values you are passing into the SQL query, using mysql_real_escape_string.
Then, you should add quotes, in your SQL query, arround the fields that are meant to contain strings.
I don't really know which fields are integers and which fields are strings, but you should be using something like this to build your SQL query :
// Escape the string data, and make sure integer really contain integers
$anInt = intval($anInt);
$Domain = mysql_real_escape_string($Domain);
$URL = mysql_real_escape_string($URL);
$Rank = intval($Rank);
$Pagerank = = intval($Pagerank);
$Google = intval($Google);
$Bing = intval($Bing);
$Yahoo = intval($Yahoo);
$Pages = intval($Pages);
$backlinks = intval($backlinks );
// Build the SQL query, using the "safe" variables
$SQL = 'INSERT INTO table (anInt, DomainName, URL, Rank, PageRank, Google, Bing, Boss, IndexedPage, Backlinks)
VALUES ($anInt, '$Domain', '$URL', $Rank, $Pagerank, $Google, $Bing, $Yahoo, $Pages, $backlinks)';
This is supposing that only DomainName and URL are meant to contain strings -- you might have to use mysql_real_escape_string and add quotes arround the values for some other fields too, if needed.
Then, you should take a look at the return value of mysql_query : for an insert query, in case of an error, it'll return false.
Here, if your $result variable is false, you should use mysql_error and mysql_errno : they'll allow you to know what error happened -- it will help detecting errors in your SQL query, for instance.
If this doesn't solve the problem, you should try outputting the SQL query, and run it using something like phpMyAdmin, to make sure it's OK.
I am no PHP expert, but I have 2 remarks.
You don't check the error (perhaps with mysql_errno()) so you don't know whether the records were added
I think the values, if they are strings, should be given like
'$Domain'
that is, escaped with ' characters.
better would be, of course, using something like
$sql = sprintf("INSERT ... VALUES(%d, '%s', '%s',...)",
$anInt, mysql_real_escape_string($Domain), ...);
if you insert user-supplied input.
You could examine the $result:
$result = mysql_query($query);
if (!$result) {
print "An error occured: " . mysql_error() . "\n";
}
My guess is that you're passing a string without quotes, like:
VALUES (Hello)
where you should pass it like:
VALUES ('Hello')
Like the commenter said, if the user can control these strings, you are open to an SQL Injection attack. You can prevent that attack by escaping the strings, for example:
$query = sprintf("INSERT INTO table (DomainName) VALUES ('%s')",
mysql_real_escape_string($domain_name));
In SQL queries, you need to enquote strings correctly, or it will produce an error. So all your variables that are used to store non-int or non-boolean values in the database need quotes around the values.
Additionally you should make sure that SQL injections are not a problem by escaping all values with mysql_real_escape_string first.
Apart from sql injections your error handling is not complete...
if (!$db_found) {
echo "datbase not found.";
}
else {
$SQL = 'INSERT INTO
table
(...)
VALUES
(...)
';
$result = mysql_query($SQL, $db_handle);
if ( !$result ) {
echo "error: ", mysql_error($db_handle);
}
else {
print "Records added to the database";
}
}
mysql_close($db_handle);
In case a query causes an error mysql_query() return FALSE and mysql_error() will tell you more about the error.
Well there are security issues with the code but to address one problem
you are not enclosing your string values in quotes in the SQL statement.
First of all, please regard everybody else's advice on safe database handling and avoiding injection.
The reason your query isn't doing anything is probably that you enclosed the string in single quotes. In PHP single quotes enforce the string to be literal. Unlike when using double quotes, variables will NOT be substituted. So '$foo' represents the sequence of characters '$'.'f'.'o'.'o'. "$foo" on the other hand represents the sequence of characters of whatever the variable $foo contains at the time of the string's definition.
You can use mysql_error() to catch most problems with MySQL. Even if the message isn't helping you, you at least know whether the query was parsed properly, i.e. on which end of the connection the problem lies.