What does the parameter do for the if statment? - php

What does this loop do? I don't know what it means. I've already tries using the internet to find out what the parameter does but I couldn't find anything.
if (mysqli_query($conn, $sql)) {
echo "Table Game Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

Functions like mysqli_query return a value, in this case a boolean which is either 0 or false (0) if it fails to execute properly (Its like your fridge has a function too, you put in milk and cold milk is returned but fails to do so if the outlet is not plugged in) and returns an object if it executed properly.
The thing with querys is that we always want to verify if a query is successful or not.
if(true){
# execute this code
} else {
# otherwise execute this block of code
}
if(($result = mysqli_query($conn, $sql)) != false){ #Translates to: If $result is not equal to false execute the following code.
# use $result here to print out data.
} else {
# failed the query cause $result equals to false.
}
Its programming logic 1:1, instead of trying to figure out what that function does try to do some basic stuff in the language first.

Related

MS Access & php

What is the correct condition for the if statement in the code below
$sql = "INSERT INTO table ($columns) VALUES ($values)";
echo $sql;
$results = odbc_exec($conn, $sql);
if ($results){
echo "Query Executed";
}else {
echo "Query failed " .odbc_error();
}
or should it be
if ($results > 0){
Please advise.
From the manual: http://php.net/manual/en/function.odbc-exec.php
Returns an ODBC result identifier if the SQL command was executed
successfully, or FALSE on error.
So checking for a $result is OK:
<?php
...
$result = odbc_exec($conn, $sql);
if ($result) {
// OK
} else {
// Failure
}
The correct way to test odbc_exec() for success or failure is:
if ($result !== false) {
// success
} else {
// failure
}
The documentation says:
Returns an ODBC result identifier if the SQL command was executed successfully, or FALSE on error.
If a function returns a boolean (FALSE) or non-boolean values, be sure to use the identity comparison operator.
While if ($result) may work in this case (it depends on possible ODBC result identifiers), it will not work in other cases.
For example, strpos() returns FALSE if the substring is not found and the position of the substring otherwise - that means 0 is a positive result.
if ($result) would be wrong in this case while if ($result !== FALSE) will work as expected.

$result is showing true every time

i just started learning PDO...
function authenticate($username,$password)
{
$result=$this->con->query("select * from user where UserName='".$username."' AND Password='".$password."'");
var_dump($result->rowCount()); //return null
if($result)
echo "hey going great";
else
echo "Hey are you gone mad?";
}
i am calling above function with username and password... but it's returning hey going great part every time if i will pass wrong username and password also...
i tried with $result->rowCount() but it's also returning null value...
Can you suggest me what i am doing wrong here?
You are doing almost everything wrong.
First and foremost, the only reason for using PDO is using placeholders in the query.
You shouldn't also check the query result right in the function. So, make it
function authenticate($username,$password)
{
$sql = "SELECT * FROM user WHERE UserName=? AND Password=?";
$stm = $this->con->prepare($sql);
$stm->execute([$username,$password]);
return $stm->fetch();
}
and then call
if($userdata = $user->authenticate($username,$password))
echo "hey going great";
else
echo "Hey are you gone mad?";
Assuming $this->con is an instance of PDO:
PDO->query() only returns false on failure.
$result will be an instance of PDOStatement, which always evaluates to true
PDOStatement->rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
Edit: By the way, your application would be more safe, if you use PDO->prepare() (& bound parameters) instead of PDO->query().
if($result)
This will always check for if the variable has any info. When ever you run a query and store in this var , it will store number of rows returned . Even if it is wrong , it will return a neg value which sets the variable.
Basically your if is just checking if the variable exists , it does exist in both cases.
if($result->rowCount()>0){
echo "hey going great";
}else{
echo "Hey are you gone mad?";
}
you can try it as:
$result=$this->con->query("select * from user where UserName='".$username."' AND Password='".$password."'");
var_dump($result->rowCount()); //return null
$num_row=$result->rowCount();
if($num_row > 0)
echo "hey going great";
else
echo "Hey are you gone mad?";

PHP or die and if else conditional idiosyncrasies

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.

php if sql query returns valid result

I'm sure this is a simple fix, I want to run a code block if an sql query comes back with a positive result. something like:
if($query = mysqli_query($cxn,"[query]"))
{
Code to be executed if the query returns a positive result
}
I have tried this format but doesn't work. I'm sure I have done this before but I'm running in to a wall here.
Hope you can help.
As stated in php.net/manual/mysqli.query.php, mysqli_query will:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
You should for you next question specify what you mean by positive result. But this code will see if there was an error, if the query returned an empty set, and so on... (I have not tried to run the code)
$result = mysqli_query($cxn,"[query]");
if ($result === FALSE) {
echo "There was an error";
}
else if ($result === TRUE) {
echo "The query was successful (a query that didn't return anything)";
}
else if (mysqli_num_rows($result) == 0) {
echo "The result is empty"
}
else {
echo '$result contains data';
}
So you mean if the query doesn't fail? then:
$query = mysqli_query($cxn, "[query]");
if($query !== false) {
// Code to be executed if the query returns a positive result
}

PHP MySQL query not working

I'm having trouble with this long sql query. If I change $result= mysql_query( to an echo statement and copy the resulting string into MySQL, it adds the data into the db just fine. It's only when I'm using PHP to do it that it fails.
Code:
$con = mysql_connect("-","-","-");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else {
// connected to database successfully
}
mysql_select_db("casemanagers", $con);
$result= mysql_query("INSERT INTO `criminal` (`JudgeID`, `Month`, `Year`, `PendingCapDefs`, `PendingCapCases`, `PendingNonCapDefs`, `PendingNonCapCases`, `AsgNewCapDefs`, `AsgNewCapCases`, `AsgNewNonCapDefs`, `AsgNewNonCapCases`, `AsgTRCapDefs`, `AsgTRCapCases`, `AsgTRNonCapDefs`, `AsgTRNonCapCases`, `AsgRCCapDefs`, `AsgRCCapCases`, `AsgRCNonCapDefs`, `AsgRCNonCapCases`,
`DispGPCapDefs`, `DispGPCapCases`, `DispGPNonCapDefs`, `DispGPNonCapCases`, `DispDDCapDefs`, `DispDDCapCases`, `DispDDNonCapDefs`, `DispDDNonCapCases`, `DispNPCapDefs`, `DispNPCapCases`, `DispNPNonCapDefs`, `DispNPNonCapCases`, `DispODCapDefs`, `DispODCapCases`, `DispODNonCapDefs`, `DispODNonCapCases`, `DispBTACapDefs`, `DispBTACapCases`, `DispBTANonCapDefs`, `DispBTANonCapCases`, `DispBTCCapDefs`, `DispBTCCapCases`, `DispBTCNonCapDefs`, `DispBTCNonCapCases`, `DispJTACapDefs`, `DispJTACapCases`, `DispJTANonCapDefs`, `DispJTANonCapCases`, `DispJTCCapDefs`, `DispJTCCapCases`, `DispJTCNonCapDefs`, `DispJTCNonCapCases`, `DispADDCapDefs`, `DispADDCapCases`, `DispADDNonCapDefs`, `DispADDNonCapCases`, `DispSCDCapDefs`, `DispSCDCapCases`, `DispSCDNonCapDefs`, `DispSCDNonCapCases`, `DispCTOCapDefs`, `DispCTOCapCases`, `DispCTONonCapDefs`, `DispCTONonCapCases`, `OldCapDefs`, `OldCapCases`, `OldNonCapDefs`, `OldNonCapCases`) VALUES ('$judgeID',' $month',' $year',' $PendingCapDefs','$PendingCapCases','$PendingNonCapDefs','$PendingNonCapCases','$AsgNewCapDefs','$AsgNewCapCases','$AsgNewNonCapDefs','$AsgNewNonCapCases','$AsgTRCapDefs','$AsgTRCapCases','$AsgTRNonCapDefs','$AsgTRNonCapCases',' $AsgRCCapDefs','$AsgRCCapCases','$AsgRCNonCapDefs',' $AsgRCNonCapCases','$DispGPCapDefs','$DispGPCapCases','$DispGPNonCapDefs','$DispGPNonCapCases','$DispDDCapDefs','$DispDDCapCases','$DispDDNonCapDefs','$DispDDNonCapCases',' $DispNPCapDefs',' $DispNPCapCases',' $DispNPNonCapDefs','$DispNPNonCapCases','$DispODCapDefs',' $DispODCapCases','$DispODNonCapDefs','$DispODNonCapCases','$DispBTACapDefs','$DispBTACapCases','$DispBTANonCapDefs','$DispBTANonCapCases','$DispBTCCapDefs','$DispBTCCapCases','$DispBTCNonCapDefs','$DispBTCNonCapCases','$DispJTACapDefs','$DispJTACapCases','$DispJTANonCapDefs','$DispJTANonCapCases','$DispJTCCapDefs','$DispJTCCapCases','$DispJTCNonCapDefs','$DispJTCNonCapCases','$DispADDCapDefs','$DispADDCapCases','$DispADDNonCapDefs','$DispADDNonCapCases','$DispSCDCapDefs','$DispSCDCapCases','$DispSCDNonCapDefs','$DispSCDNonCapCases','$DispCTOCapDefs','$DispCTOCapCases','$DispCTONonCapDefs','$DispCTONonCapCases','$OldCapDefs','$OldCapCases','$OldNonCapDefs','$OldNonCapCases');");
if ($result==1){
$statusCaption = 'New Civil Report';
echo 'Report Successfully Saved!<br/><br/><-- Back to User Menu';
}
else {
$statusCaption = 'Error';
echo 'There was a problem with one or more of your entries. Please try again.<br/><br/><--Back to Civil Report';
}
mysql_query() returns a statement handle on success, or boolean false on failure/errors. It'll never return an integer '1'.
if ($result !== false) {
... success ...
} else {
... failure ...
}
Note that 'failure' is only due to a syntax error in the query or a violation of a constraint in the db or a failure in the client-server communications link. A select query that returns no rows is NOT a failure. It's just a result set that happens to contain no rows.
$result= mysql_query("INSERT INTO `criminal` VALUES ('$judgeID',' $month',' $year',' $PendingCapDefs','$PendingCapCases','$PendingNonCapDefs','$PendingNonCapCases','$AsgNewCapDefs','$AsgNewCapCases','$AsgNewNonCapDefs','$AsgNewNonCapCases','$AsgTRCapDefs','$AsgTRCapCases','$AsgTRNonCapDefs','$AsgTRNonCapCases',' $AsgRCCapDefs','$AsgRCCapCases','$AsgRCNonCapDefs',' $AsgRCNonCapCases','$DispGPCapDefs','$DispGPCapCases','$DispGPNonCapDefs','$DispGPNonCapCases','$DispDDCapDefs','$DispDDCapCases','$DispDDNonCapDefs','$DispDDNonCapCases',' $DispNPCapDefs',' $DispNPCapCases',' $DispNPNonCapDefs','$DispNPNonCapCases','$DispODCapDefs',' $DispODCapCases','$DispODNonCapDefs','$DispODNonCapCases','$DispBTACapDefs','$DispBTACapCases','$DispBTANonCapDefs','$DispBTANonCapCases','$DispBTCCapDefs','$DispBTCCapCases','$DispBTCNonCapDefs','$DispBTCNonCapCases','$DispJTACapDefs','$DispJTACapCases','$DispJTANonCapDefs','$DispJTANonCapCases','$DispJTCCapDefs','$DispJTCCapCases','$DispJTCNonCapDefs','$DispJTCNonCapCases','$DispADDCapDefs','$DispADDCapCases','$DispADDNonCapDefs','$DispADDNonCapCases','$DispSCDCapDefs','$DispSCDCapCases','$DispSCDNonCapDefs','$DispSCDNonCapCases','$DispCTOCapDefs','$DispCTOCapCases','$DispCTONonCapDefs','$DispCTONonCapCases','$OldCapDefs','$OldCapCases','$OldNonCapDefs','$OldNonCapCases');") or die(mysql_error());
try it
BTW, you're probably missing a lot of variables
try to add
or die(mysql_error());
just after query
it will give you answer/error/tell you what's wrong.
Please read the PHP.net page. The function mysql_query() does not return true/false. It only returns false when there was an error. Your code should look like this:
if ($result === false) {
//error
}
else {
//success
}
That way you only see the error occurs when it REALLY REALLY returns false.
EDIT: Also, I never include ; in the actual query in your PHP code when you have one query. That is a query delimiter and is only needed in command prompt or when you are executing two queries in the same mysql_query() instance.

Categories