Statements in php - php

if($getstatus->num_rows != 0 && $getstatusarr = $getstatus->fetch_assoc() && $getstatusarr["Type"] != $data["type"])
echo "error"
else
...
first code will not work, to make works this way, see Nin's post
Is it possible to make the code easily?
Also I can do it like this:
if($getstatus->num_rows != 0)
$getstatusarr = $getstatus->fetch_assoc();
if($getstatusarr["Type"] != $data["type"]) {
echo "error"
$error = true;
}
if(!$error) {
...
}
by ellipsis I have too many lines of code :)
added:
also I can do in this way:
if($getstatus->num_rows != 0) {
$getstatusarr = $getstatus->fetch_assoc();
if($getstatusarr["Type"] != $data["type"]) {
echo "error";
goto skip;
}
}
... // some code which I need not to execute if $getstatusarr["Type"] != $data["type"] are true
skip:
// another code which will execute in all cases

Well, don't use goto: :)
Whether you put all the if's on one line or on several lines is mostly a personal preference.
Too many lines with if will make the code harder to read but putting it all on one line also makes it difficult to read and difficult to debug (error on line 12 can mean many things then). If you're using a debugger like xdebug or Zend debug then having multiple lines to step over is also easier.
So find a way in between this.
I would do it like this, since then you also check if fetch_assoc() returned a result:
if($getstatus->num_rows != 0 && $getstatusarr = $getstatus->fetch_assoc())
if($getstatusarr["Type"] != $data["type"]) {
echo "error"
$error = true;
}
if(!$error) {
...
}

From my point of view is always best to unwrap statements and clean the code as much as you can, maybe someone later on will have to read what you did and he will have a hard time doing that.
Also you cannot assign new variables in a if statement like that:
$error = false;
if($getstatus->num_rows)
$getstatusarr = $getstatus->fetch_assoc();
if($getstatusarr["Type"] != $data["type"]) {
$error = array('type' => 'invalid type');
}
}
if($error) {
// do something with $error array
}

Related

Running through if/else statement and getting lost

I'm having a brain dead moment and getting lost in my logic, please can someone help!
I'm looking to recreate 3 scenarios:
If downloads AND resources exist.
If only downloads exist.
If only resources exist.
These are decided by the two statements:
Downloads = have_rows('downloads')
Resources = get_sub_field('resources')
How can I run through the 3 scenarios in an if/else loop?
$downloads = have_rows('downloads');
$resources = get_sub_field('resources');
if($downloads && $resources) {
// do something
} elseif($downloads) {
// do something else
} elseif($resources) {
// yet another something else
}
If I correctly understood your question
if(have_rows('downloads') && get_sub_field('resources'))
{
//some stuff
}
else if(have_rows('downloads'))
{
//Some other stuff
}
else if(get_sub_field('resources'))
{
//More stuff
}
Something like this???
$bDL = have_rows('downloads');
$bRE = get_sub_field('resources');
// If downloads AND resources exist.
if ($bDL && $bRE){
}
// If only downloads exist.
if ($bDL && !$bRE){
}
// If only resources exist.
if (!$bDL && $bRE){
}

Php error Working with get varialbes

i have a php code and when i add some gets variables i get error, 500, i tested it with ajax and without ajax(directly writing the url on the adress bar)
When i go with localhost/ajax/test.php?did=1 everything is fine but when i go with localhost/ajax/test.php?did=1&task=1 the problem happens
all the functions are created before on the ../php/core.php
Here is the code
<?php
require '../php/core.php';
$did = floor($_GET['did']);
if (device_exist($did) && amlogedin() && intouch_get($uid, $did) == 2) {
$task = floor($_GET['task']);
$id = safestring($_GET['id']);
switch ($task) {
case 1:
if (feature_removefeature($did, $fid)) {
echo donemsg("Feature Removed");
}
break;
}
design_makefeturelist($did);
}
else {
echo 'Sorry, some thing is wrong';
}
Almost sure that you've got an error in the feature_removefeature or donemsg function. Because after you set task=1 it will enter the case 1: statement. You could replace the if with a simple echo "lala"; to check it out.
ps. Is $fid already set?

Break Parent IF (Conditional)

How can i break parent if in PHP?
example this code:
if(true){ // This is parent conditional
if(true) { // This is child conditional
break parent conditinal
}
}
afterBreakDoMe();
From code above. I want when child conditional is true. Then it break parent conditional (exit from that conditional) and continue the rest of the code (afterBreakDoMe()).
Update - Real code
$errorMessage = '';
if(isset($_POST) && count($_POST)) { // Detect some user input
// validation
$countryName = trim($_POST['countryName']);
if($countryName == ''){ // validation user input, if false. exit from parent if and continue show html input (refer to $Render->output())
$errorMessage = 'Name must not be empty!';
}
header('Location: '.$baseUrl.'&page=tableShipping');
}
$Render->setTitle('Create New Country');
$form = $Render->parser('createCountry', array(
'errorMessage' => $errorMessage,
));
$Render->addContent($form);
$Render->output();
You cannot do that (except using goto, which is taboo), and should not do that. Swapping functionality for simplicity is a bad idea.
Based on your "real" code, your program flow doesn't make sense.
if($countryName == ''){ // validation user input, if false. exit from parent if and continue show html input (refer to $Render->output())
So, if it's true, you're going to set $errorMessage, then exit, leave the page, and never use it again? Why? You might as well just forget the error message, call the header(), then call exit;.
I've created the following code based on what I think you want to happen, and commented it as an explanation:
$errorMessage = '';
if(isset($_POST) && count($_POST)) { // Detect some user input
// validation
$countryName = trim($_POST['countryName']);
if($countryName == ''){ // validation user input, if false. exit from parent if and continue show html input (refer to $Render->output())
$errorMessage = 'Name must not be empty!';
} else {
// If there is no error, continue forward.
header('Location: '.$baseUrl.'&page=tableShipping');
exit; // Leave the page execution since you've applied a header.
}
}
// This will only execute if there is an error, since we left the page otherwise.
$Render->setTitle('Create New Country');
$form = $Render->parser('createCountry', array(
'errorMessage' => $errorMessage,
));
$Render->addContent($form);
$Render->output();
All in all, consider the flow of your program in order to determine what happens next, not what to skip.
You could use a variable and an extra if-statement:
$errorMessage = '';
$emptyCountry = false;
if(isset($_POST) && count($_POST)) { // Detect some user input
// validation
$emptyCountry = trim($_POST['countryName']) == '';
if($emptyCountry){ // validation user input, if false.
$errorMessage = 'Name must not be empty!';
}
header('Location: '.$baseUrl.'&page=tableShipping');
}
if (!emptyCountry) {
$Render->setTitle('Create New Country');
$form = $Render->parser('createCountry', array(
'errorMessage' => $errorMessage,
));
$Render->addContent($form);
}
$Render->output();
Simple
if (true) {
if (true) {
// Do stuff
// It will then break automaticly
// but if the condition here is false you got the else ;)
} else {
}
}
Use goto. This is used for jumping in code
Now that I can read the real code sample I think what you need to do is simple put all the conditionals together in a single. Using goto will get the job done but can easily make you code hard to read and maintain. Perhaps its time to rethink the program flow.
Anyway, what I am saying is something like this:
if(!empty($_POST) && isset($_POST['countryName']) && (trim($_POST['countryName']) == '')){
$errorMessage = 'Name must not be empty!';
}
...
$errorMessage = '';
do {
if(isset($_POST) && count($_POST)) { // Detect some user input
// validation
$countryName = trim($_POST['countryName']);
if($countryName == ''){ // validation user input, if false. exit from parent if and continue show html input (refer to $Render->output())
$errorMessage = 'Name must not be empty!';
break;
}
header('Location: '.$baseUrl.'&page=tableShipping');
}
while(false);// only for break

If else block in PHP

I don't know where I am going wrong in else if logic...
I want to validate this signup script in 3 steps:
1st: check if any field is empty, in which case include errorreg.php and register.php.
2nd: If email already exists include register.php.
3rd: If all goes well insert data to the database.
<?php
$address =$_POST["add"];
$password =$_POST["pw"];
$firstname =$_POST["fname"];
$lastname =$_POST["lname"];
$email =$_POST["email"];
$contact =$_POST["cno"];
$con=mysql_connect("localhost","root","");
mysql_select_db("bookstore");
$q2=mysql_query("select * from customer where email='$email'");
$b=mysql_fetch_row($q2);
$em=$b[0];
if($password != $_POST['pwr'] || !$_POST['email'] || !$_POST["cno"] || !$_POST["fname"] || !$_POST["lname"] || !$_POST["add"])
{
include 'errorreg.php';
include 'register.php';
}
else if($em==$email)
{
echo 'email already present try another';
include 'register.php';
}
else
{
$con=mysql_connect("localhost","root","");
mysql_select_db("bookstore");
$q1=mysql_query("insert into customer values('$email','$password','$firstname','$lastname','$address',$contact)");
echo 'query completed';
$q2=mysql_query("select * from customer where email='$email'");
$a=mysql_fetch_row($q2);
print "<table border =2px solid red> <tr><th>id </th></tr>";
print "<td>$a[0]</td>";
print "</table>";
include 'sucessreg.php';
echo " <a href='newhome.php'>goto homepage</a>";
}
?>
There's a lot to correct here, but to your specific concern, that the "loop" doesn't go on to the second and third "steps", that's because you're thinking about this wrong. In an if/else if/else code block, only one of the blocks is executed at a time, the others are not. For instance, if a user submitted a number, we could tell them it was even or odd with the following:
if($_GET['number'] % 2 == 0){
echo "That's even!";
} else {
echo "That's odd!";
}
You are attempting to do one check, then another, then a third. In this case, you want to nest your conditionals (if statements) rather than have them come one after another, like so:
if(/* first, basic sanity check*/) {
if(/* second, more complex check */) {
if(/* final check */) {
// Database update
} else {
// Failed final check
}
} else {
// Failed second check
}
} else {
// Failed basic check
}
Some other comments on your code:
Pay attention to formatting - laying out your code in consistent and visually clear patterns will help make it easier to see when you make a mistake.
Use isset($_POST['variable']) before using $_POST['variable'], otherwise you'll get errors. One idea is to use lines like: $address = isset($_POST['address']) ? $_POST["add"] : ''; - if you don't know that notation, it lets you set $address to either the value from the $_POST array or '' if it's not set.
Use the variables you created, like $email and $contact, rather than re-calling the $_POST variables - they're clearer, shorter variable names.
Use the better MySQLi library, rather than the MySQL library.
Create one connection ($con = ...) to your database at the beginning of your script, and don't create a second one later on, like you do here.
Explicitly specify which connection your queries are running against - you say $q2=mysql_query("SELECT ...") but you should also pass the connection you've constructed,
$q2=mysql_query("SELECT ...",$con).
First of all you want to check if the property isset in your $_POST object:
if(isset($_POST["name"])
second you want to check if the value set is empty
if(isset($_POST["name"] && !empty($_POST["name"]))
now you just have to scale it up to check all your properties it would be handy to move it into a function like this
function ispostset($post_var)
{
if (isset($_POST[$post_var]))
{
if ($_POST[$post_var] != '')
{
return true;
}
else
return false;
}
else
return false;
}

can you prevent a php while loop from erroring out?

I was wondering if there was a way to prevent a while loop from prematurely erroring out or terminating. I've thrown a try/catch in there and it seems to keep terminating. (As to the cause why it's terminating, I'm still debugging).
$stomp = $this->stomp;
if(isset($queue) && strlen($queue) > 0) {
error_log('Starting Monitor for: '.$queue);
$stomp->subscribe($queue);
while(true) {
$frame = $stomp->readFrame();
if ($frame != null) {
// Callback must be an array: array('Class','Method);
if(is_array($callback) && count($callback) == 2) {
try {
$body = $frame->body;
$callFunct = call_user_func_array($callback,array($body,$arguments));
$stomp->ack($frame);
} catch(StompException $e) {
$msg = 'Stomp Monitor readFrame() Callback Fail: '.$e->getMessage();
$this->context->reportError('STOMP',array('errorDetails'=>$msg));
}
} else {
error_log('Invalid Stomp Callback');
}
}
}
} `
Thanks,
Steve
There's nothing to break out of the loop, so while(true) will carry on until it hits a timeout or some form of error condition. As a fallback, it's worth setting either a break to break out of the loop on condition, or use a while condition that you can set to false;
while (true) {
// do some things
break;
}
or
$x = true;
while ($x) {
// do some things
$x = false;
}
that way, exit from the loop is under your control
However, timeouts and other fatal errors still terminate the script as normal
If your code is breaking out of the while loop, you should be seeing some error, unless you have an error handler suppressing it

Categories