So I have this code in a php file:
$query="INSERT INTO tec (name) VALUES ('$name')";
$done=mysql_query($query);
if($done == 'null') {
$output = json_encode(array('type'=>'error', 'message' => $mess['error'].$done.'</b></div>'));
} else {
$output = json_encode(array('type'=>'success', 'message' => $mess['success']));
}
It inserts a name into a table named "tec". If $done == 'null' then I print an error message.
The problem is that when I run the code, it inserts the data correctly, but I get the error message.
I tried to read $done and its equal to 1.
Should I do something like:
if($done == 1){
//OK
}else{
//NOT OK
}
Or is there any way to fix this?
The documentation says that mysql_query returns FALSE on error. That means instead of testing whether it's equal to 'null' (a string which compares as TRUE), you could just test the boolean-ness directly:
if($done){
//OK
}else{
//NOT OK
}
I would be remiss if I didn't mention that the mysql_* family of functions is deprecated, unsafe, and will be removed from future versions of PHP! Instead, I can personally recommend PDO, which I've used with a good amount of success.
As per the documentation of mysql_query function's php manual
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
So, search if it's TRUE or FALSE.
if ($done == TRUE) {
Hi I think you should use boolean
just try this (you'd better use mysqli instead mysql
if(!done)
{
// something wrong
echo mysql..
}
else
{
// everything works fine....
}
The error catching must be like the following:
if($done === false){
//NOT OK
}else{
//OK
}
But as #John Conde mentioned do not use mysql_* because its deprecated.
Related
I am lost a bit, shifting from regular queries to parametrized and it seems I cannot get an error.
I know for sure sql does not perform INSERT but also there is no error displayed.
How do I see errors with execute statements? The actual query has 50 values. Below is a code smaple, I just need ot know how to pull errors on execute. Thank you!
$sqlParamsArUpd = array('10', '20')
$data = $conn->prepare($sqlNew);
$data->execute($sqlParamsArUpd);
if ($data) {
// code continues here (SQL does not insert values and code simply continues here, instead of showing error
} else {
print_r($conn->errorInfo())
}
Use the boolean from PDOStatement::execute
$sqlParamsArUpd = array('10', '20')
$stmt = $conn->prepare($sqlNew);
$inserted = $stmt->execute($sqlParamsArUpd); // Returns true or false
if ($inserted) {
echo $stmt->rowCount()." rows inserted";
} else {
print_r($stmt->errorInfo())
}
I have function that performs a mysql_query() and then does some other stuff.
I want to be able to perform another mysql_query() only if the first one succeeds.
Here is the function
function myFunction($qtext)
{
mysql_query($qtext) or die(mysql_error() . "\n");
//do some more stuff
return true;
}
I'm calling the function and attempting to check if it failed with an if else conditional...
if(!myFunction($query_text))
{
echo "first query failed";
}
else
{
mysql_query($query_text1) or die (mysql_error() . "\n");
}
This seems to work when the first query passes, but if the first query fails it goes to the or die and returns the mysql_error() text and the echo "first query failed"; line in the conditional is never reached.
Ideally id like to be able to alert the user with the mysql_error text but without or dieing, so I can run more code in the conditional.
Any help with explanations of behavior is greatly appreciated.
Thanks.
p.s.
I'm a beginner... I'm not sure if Im using the return true; properly in the function
You're always returning true in the function - you need to also return false if you're checking it in an if() statement.
function myFunction($qtext) {
// run the query
$sql = mysql_query($qtext);
// see if there was a result (or whatever you're checking)
if(mysql_num_rows($sql) > 0) {
// do some more stuff
return true;
} else {
return false;
}
}
Also, you really should learn mysqli or POD instead of mysql, as mysql is depreciated. I also recommend you don't use die() unless you're testing. Build an error handling function instead - it's actually quite easy and will handle errors gracefully instead of abruptly killing the script and annoying your users. You also don't want to print error messages directly to your browser because it can compromise your site's security. :)
Just an FYI: I use a database class and run my queries like this. It's fast and clean.
if($db->get_results("SELECT email FROM users WHERE email='".$db->escape($email)."'")) {
return true;
} else{
return false;
}
To prevent "or die" from happening, replace it with return false:
function myFunction($qtext)
{
$result = mysql_query($qtext);
if ($result === false)
{
return false;
}
//do some more stuff
return true;
}
that way your check later on will work and condition will fire. You don't have to use "or die", that is reserved for the cases where you want to halt all execution.
die() kills the script instantly. That function will never return any value if you call die() inside it, you will never be able to perform other queries. Only the destructors of instanced object are still ran after a die() call, and with several restrictions.
If you want to be able to continue doing stuff after a query fails, you must never call die(). Instead, just check if mysql_query() returned FALSE as Tim suggested. Note the === operator, its important to a proper error check here.
If you still want to print the error like die() would, use print() or echo instead.
hello i would like to transform a mysql-function into a mysqli version. this function is for checking if an user exists or not. so i'm new to functions and even to mysqli. thats why i'm having problems while transforming it.
the mysql-version is:
function a($uname){
return (mysql_result(mysql_query("SELECT COUNT (`a`) FROM `table_1` WHERE `a`='$uname'"), 0) == 1) ? true : false;
}
the mysqli-version i thought would be:
function a($uname){
return (mysqli_num_rows(mysqli->query("SELECT COUNT (`a`) FROM `table_1` WHERE `a`='$uname'"), 0) == 1) ? true : false;
}
i know that there is no mysql_result anymore. i decided to use mysqli_num_rows. but this function does not work and i have no clue why. error_reporting is enabled but when calling the page, i will get a blank page with no error messages?!
so if there is someone who could help me out i really would appreciate.
thanks alot.
You need a helper function to put all dirty mysqli internals behind the scenes.
Like safemysql. It can mimic mysql_result as well:
function a($uname){
global $db; // with mysqi you have to connect once and then use this connection
return (bool)$db->getOne("SELECT COUNT (1) FROM table_1 WHERE a=?s"), $uname);
}
and can solve dozens of similar issues.
Freely from the documentation:
mysqli->query returns either a mysqli_result object for queries, which actually return some results, 'false' for failed queries and 'true' for all other queries (if successful).
You will not know anything about the result of your query, unless you check the result more thoroughly.
Try something like this: (This assumes that the connection has been successfully established, and that $uname has been properly escaped.)
function a($uname) {
$found = false;
$result = mysqli->query("SELECT `a` FROM `table_1` WHERE `a`='$uname'");
if($result) {
//We used a 'SELECT' query and the query was successful. That means, we now have a mysqli_result object.
$found = ($result->num_rows == 1); //Determines, if something was actually found or not.
$result->close(); //Frees some ressources. Not necessary, but doesn't hurt either.
} else { //The query failed, as such we have nothing to evaluate.
die("Queryerror: ".mysqli->error);
}
return $found;
}
I changed the query parameter from 'COUNT' to 'a', because otherwise 'num_rows' will ALWAYS return 1, even if the actual count is '0'. This way, it returns the number of matched rows, essentially return '0' for 'no match' or '1' for 'match'.
So I want to do a mysql_query - and I want to tell if a resource is null (that is, was unable to pull any values). Would the query be returned as false if no values were present? Am I reading the documentation right on this?
You can count the number of returned rows with mysql_num_rows(), and check how many were received from the query.
$results = mysql_query("SELECT * FROM...");
if(mysql_num_rows($results) > 0 ) {
// Got some results
} else {
//no rows
}
However note that if the query failed due to an invalid SQL or some other reason, $results will be false, so you can just do:
if(!$results) {
// Query was invalid
}
You would use mysql_num_rows() for this.
If mysql_query() returns FALSEit means there was an actaul problem with the query operation, not that there were no rows returned.
The flow goes something like this:
$query = "SELECT * FROM wherever";
if (!$result = mysql_query($query)) {
// mysql_error() gives a human readable string that explains what went wrong
// You should **never** show it in a production environment!
die('MySQL Error: '.mysql_error());
}
if (!mysql_num_rows($result)) {
// There were no results
} else {
// There were some results
}
This is only true for queries that return data (SELECT, DESCRIBE etc) - queries that just perform an action (INSERT, UPDATE, DELETE etc) will always return TRUE if the action was successful, or FALSE if it failed.
From the manual:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
If there are no records to return, mysql_num_rows($resultHandle) would return 0 (zero)
No, mysql_query will return a resource (not FALSE) also if your SELECT query do not return any rows. To check if no rows have been returned, you can use a bounch of functions:
http://www.php.net/manual/en/function.mysql-num-rows.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
...
Manual
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
To check if it's success, it might be a good idea to use isset or !empty:
$rs = mysql_query("select 1");
if (!empty($rs)){
//everything ran fine
}
else{
//something broken
}
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.