both if and else statements excecuting - php

I've got a weird problem: both my if and else statements are executing. Here's my code:
if ($sel_user['name'] != $name) {
$query = "UPDATE owner SET
..."
$result = mysql_query($query);
if (mysql_affected_rows() ==1) {
$query2 = "UPDATE queue_acl SET
..."
$result2 = mysql_query($query2);
if (mysql_affected_rows() ==1) {
$_SESSION['updates_occurred'] = true;
} else {
$_SESSION['updates_occurred'] = false;
}
}
}
if ($sel_user['orgId'] != $orgId) {
$query = "UPDATE ownerOrganization SET
..."
$result = mysql_query($query);
if (mysql_affected_rows() ==1) {
$query2 = "UPDATE queue_acl SET
..."
$result2 = mysql_query($query2);
if (mysql_affected_rows() ==1) {
$_SESSION['updates_occurred'] = true;
} else {
$_SESSION['updates_occurred'] = false;
}
}
}
if ($sel_user['date_expires'] != $colVal[0] ||
$sel_user['admin'] != $colVal[4]) {
$query3 = "UPDATE queue_acl SET
..."
$result3 = mysql_query($query3);
if (mysql_affected_rows() ==1){
$_SESSION['updates_occurred'] = true;
} else {
$_SESSION['updates_occurred'] = false;
}
} else {
$_SESSION['updates_occurred'] = false;
$message = "<i>There were no edits to apply</i>";
}
When I run this, the queries are being sent and everything is being updated fine, but the "There were no edits" message is also being printed
Anyone know why?
EDIT: I do not want to use elseif statements; the events are not mutually exclusive. That is, if $sel_user['name'] != $name AND $sel_user['orgId'] != $orgId, it is required that both queries are sent

If you don't want to wrap everything in an if/else if statements, one could set a flag at the end of each if check.
if($sel_user['name'] != $name) {
// CODE HERE
$flag = true;
}
if(!$flag){
$message = "<i>There were no edits to apply</i>";
}
It's that or you can run the if check off $_SESSION['updates_occurred']

Instead of doing lots of ifs, you should be doing elseifs
i.e.
if () {
} elseif () {
} else {
}
hope that helps.

if(!printf("Hello")) {
echo "Hello";
}
else {
echo " World";
}

Related

IF/ELSE condition in sql and php

I'm inserting into my database id and hours, which is working successfully. However when i insert a new value for an id that has a previous value, the old val isn't replaced by the new, instead they're kept both. I'm trying to update the function with an if/else statement (commented part). But still the same result. The if/else statement must check first if hours (a column in the table) value is empty, if so then perform sql insert, else perform sql update. Any help please?
if (isset($_POST['submit'])) {
$hours = $_POST['Hours'];
$selectid = $_POST['SelectID'];
$sql1 = "INSERT INTO `editedworkhours` (`id`,`H`) VALUES('$selectid','$hours')";
$getResult = mysql_query($sql1);
if (mysql_affected_rows() > 0) {
} else {
}
$tempname = $row['Field'];
$sql2 = "UPDATE editedworkhours SET H ='" . $_GET["hours"] . "' WHERE IDNumber='" . $_GET["selectid"] . "'";
$result2 = mysqli_query($con, $sql2);
if ($con->query($sql2) === TRUE) {
} else {
}
}
echo $menu;
Try this
<?php
if(isset($_POST['submit']))
{
$addedhours = $_POST['AddedHours'];
$selectaf = $_POST['SelectAF'];
$sql1="SELECT * FROM editedworkhours WHERE AFNumber='$selectaf' and AddedWH ='$addedhours'";
$getResult = mysql_query($sql1);
$count = count($getResult);
if(!empty($count) || $count==1)
{
$tempname = $row['Field'];
$sql2 = "UPDATE editedworkhours SET AddedWH ='$addedhours' WHERE AFNumber='$selectaf'";
$result2 = mysql_query($sql2);
if (isset($result2))
{
//Data inserted
}
else
{
//Insert Failed
echo '<script>swal("Error", "Something went wrong error");</script>';
}
echo '<script>swal("Success", "Changes have been saved", "success");</script>';
}
else
{
$sql3 = "INSERT INTO editedworkhours (AFNumber,AddedWH) VALUES('$selectaf','$addedhours')";
$Result = mysql_query($sql3);
if(isset($Result))
{
echo 'Success';
}
else
{
echo 'Failed';
}
}
}
echo $menu;

Check for a multiple amount of information in a database

For my registration system, when the user registers, I want to make sure that their username, email, etc. is not taken. I have the code to check to see if the username exists, and I can probably do the same with the other stuff.
How can I do this without rewriting the block multiple times?
tl;dr: How can I check for more things in a database in a compact way?
$userquery = "SELECT * FROM users WHERE username = '$username'";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
die ("Username Already Exists.");
}
}
Use an 'OR' condition in your where clause
$userquery = "SELECT * FROM users WHERE username = '$username' OR email= '$email'";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
die ("Username/Email Already Exists.");
}
}
EDIT
ok then,
function doesitexist($mysqli,$table,$field,$value) {
$userquery = "SELECT * FROM $table WHERE $field = '$value' LIMIT 1";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
} else {
return('Error running Query');
}
}
ANOTHER EDIT just for fun. This should take an array of fields and values to check in one call.
$check = doesitexist($mysqli,'users',array('username'=>'bob','email'=>'someone#example.com'));
function doesitexist($mysqli,$table,$tocheck = array()) {
if (count($tocheck)>0) {
$where = '';
foreach ($tocheck as $field=>$value) {
$where .= $field." = '".addslashes($value)."' OR ";
}
$where = trim($where," OR ");
$userquery = "SELECT * FROM $table WHERE $where LIMIT 1";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
} else {
return('Error running Query');
}
} else {
return("No Fields/Values to check");
}
}

My function is returning false when it should return true

My function is always returning false when it should return true, and I can't find why
public function isReselling($key)
{
if ($this->validateKey($key)) {
return false;
}
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "
SELECT * FROM api_id
";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$blacklisttho = $row['Banned'];
if ($blacklisttho == 1) {
return true;
}
}
return false;
}
Well, you need to check where exactly the 'return' is beign made, and investigate based on that:
public function isReselling($key)
{
if ($this->validateKey($key)) {
die('validate fails');
return false;
}
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "
SELECT * FROM api_id
";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$blacklisttho = $row['Banned'];
if ($blacklisttho == 1) {
return true;
}
}
die('no results.');
return false;
}
and btw, you don't want to have multiple 'returns' around the code, that's bad practice.
I would change your code to something like:
public function isReselling($key)
{
$retValue = false;
if ($this->validateKey($key) === false) {
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "SELECT * FROM api_id";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
if ($row['Banned'] == 1) {
$retValue = true;
break;
}
}
}
return $retValue;
}

echo not working, at ($row=0)

<?php
$soil_ph = $_POST['soilph'];
$query = "select ph_id,ph_name,ph_from,ph_to from tbl_soilph
where '$soil_ph' between ph_from and ph_to";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
if ($row == 0)
{
echo 'Invalid or out of range';
}
else
{
$ph = $row['ph_name'];
echo $row['ph_name'];
}
}
?>
---echo not working # ($row=0)--- can someone help me?
the code above works fine it gives result, but when there's no data it doesn't show the message "invalid input"?
First of all, you should always escape your variables before using them in database queries (unless you use prepared statements, which you should):
$soil_ph = $_POST['soilph'];
$query = "SELECT ph_id, ph_name, ph_from, ph_to
FROM tbl_soilph
WHERE '" . mysql_real_escape_string($soil_ph) . "' BETWEEN ph_from AND ph_to";
$result = mysql_query($query);
To inspect whether you have any results, you should use mysql_num_rows() after making sure the query didn't fail:
if ($result && mysql_num_rows($result)) {
while ($row = mysql_fetch_array($result)) {
// do your stuff
}
} else {
// aww, nothing there
}
Further reading: MySQLi, PDO
$soil_ph = $_POST['soilph'];
$query = "select ph_id,ph_name,ph_from,ph_to from tbl_soilph
where '$soil_ph' between ph_from and ph_to";
$result = mysql_query($query);
if($result && mysql_num_rows($result)) {
while() {
}
} else {
echo 'invalid input';
}
Check this code , you have change the way you loop
if (mysql_num_rows($result) < 1) {
echo 'Invalid or out of range';
}else{
while($row = mysql_fetch_array($result)){
$ph = $row['ph_name'];
echo $row['ph_name'];
}
}
Actually mysql_fetch_array function return a single dimension array at each time execute. You can do like this:
if($results){
echo 'No Results';
}else{
while($row = mysql_fetch_array($result))
{
if(!empty($row)){
echo $row['ph_name'];
}else{
echo 'invalid';
}
}

why does this php code not work?

I have a BOOLEAN in my table, set to 0 or 1.
$test = mysql_query("SELECT status FROM mydb WHERE email = 'admin#mail.com'") or die(mysql_error());
if ($test == 0) {
echo "FF";
} elseif ($test == 1) {
echo "ON";
}
But this doesn't work, why? I tried true and false, that doesn´t work either.
You are not actually fetching the result.
$test = mysql_query("SELECT status FROM mydb WHERE email = 'admin#mail.com'");
if (!$test) {
die(mysql_error());
} else {
$res = $test;
}
$row = mysql_fetch_assoc($res);
var_dump($row);
$test is just the results from the query. You want to see if you get a row try this:
$result = mysql_query("SELECT status FROM mydb WHERE email = 'admin#mail.com'")or die(mysql_error());
$row_count = mysql_num_rows($result);
if($row_count == 0)
{
echo "FF";
}
else if($row_count == 1)
{
echo "ON";
}
If you need to know the value of status
$result = mysql_query("SELECT status FROM mydb WHERE email = 'admin#mail.com'")or die(mysql_error());
while($data = mysql_fetch_assoc($result))
{
if($data['status'] == 0)
{
echo "FF";
}
else if($data['status'] == 1)
{
echo "ON";
}
}

Categories