Running through if/else statement and getting lost - php

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){
}

Related

php check if browser tab was opened with "target=" - and what target it was

I am opening two windows in one session, which should have different behaviours. As the windows open at the same time, they are using th same options and interfering with each other. Therefore I would need to check in the code, how they were opened.
If it was opened with something like
window.open(href, target='pdf');
I would want to check this
if(tab.target = "pdf")
{
$check_target = 1
}
else
{
$check_target = 2
}
now "tab.target" does not exist - can I achieve this somehow?
Thanks!
Max
I would add a something to the url like this:
window.open(href+'?mytarget=pdf', target='pdf');
Then in your php code:
if($_GET['mytarget'] == "pdf")
{
$check_target = 1;
}
else
{
$check_target = 2;
}

Multiple IF statements in simple form validation

I am a newbie and trying to implement a simple validation script after reading up, but I can't see how I can have multiple Ifs that will only do an sql insert if all required fields are met. Rather than having the multiple else statements, what is a syntax approach for having all the form validation Ifs together and if one of them fails, then the correct error is shown and the sql is not execute?
if(isset($_POST ['submit'])){
$user_ID = get_current_user_id();
$catErr = $ratingErr = $titleErr = $textErr = "";
if (empty($_POST["category"])) {
$catErr = "Category is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["rating"])) {
$ratingErr = "Rating is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["post_name"])) {
$postErr = "Title is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["text"])) {
$textErr = "Text is required";
} else {
//DO THE INSERT BELOW!
}
//PDO query begins here...
$sql = "INSERT INTO forum(ID,
category,
rating,
post_name,
text
Use one variable for all the error messages and concatenate to it in the branches, so in the end if that variable is still empty string you won't do the insert. (And you don't need any of the empty else blocks that contain nothing but a comment.)
$err = "";
if (empty($_POST["category"])) {
$err .= "<br/>Category is required";
}
if (empty($_POST["rating"])) {
$err .= "<br/>Rating is required";
}
if (empty($_POST["post_name"])) {
$err .= "<br/>Title is required";
}
if (empty($_POST["text"])) {
$err .= "<br/>Text is required";
}
//PDO query begins here...
if($err=='')
{
$sql = "INSERT INTO forum(ID,
category,
rating,
...";
...
}
There are many solutions to your problem. Here are 3 methods of solving your issue.
You could combine all of your if statements like so:
if (empty($_POST['rating']) || empty($_POST'rating']) || ... ) { ... }
and separate them by double pipes.
You could also check the entire array:
if (empty($_POST)) $error = "There was an error!";
You could set a universal error variable and then output it.
A third solution could keep your current syntax but cut down on the amount of lines. You could save lines by doing without brackets. You can create an array and push your errors to the array.
Note: You can use empty() or isset().
// create an array to push errors to
$errors_array = array();
// if a particular field is empty then push the relevant error to the array
if(!isset($_POST['category'])) array_push($errors_array, "Category is required");
if(!isset($_POST['rating'])) array_push($errors_array, "Rating is required");
...
Once you have an array full of errors you can check for them like so:
// if the array is not empty (then there are errors! don't insert!)
if (count($errors_array) > 0) {
// loop through and echo out the errors to the page
for ($i = 0; $i < count($errors_array); $i++) {
echo $errors_array[i];
}
} else {
// success! run your query!
}
You should use javascript to validate the page before it is even processed into a post. This script will run client-side when they hit submit and catch errors before they even leave the page.
Here's a tutorial on how to do something like that: tutorial
Each field can have its own validation parameters and methods, and it will also make the page's code look a lot nicer.
I got it to go with this approach after showdev got me thinking that way. It's not very elegant perhaps, but does the trick, although all the user is taken to a blank page if there are errors and it simple says: Missing category (or whatever). Wondering if I can echo a link or something back to the page with the form from there so the user has an option like "go back and resubmit". Otherwise I will have to handle and display the errors alongside the form which will require a different approach altogether...
if(isset($_POST ['submit'])){
$errors = false;
if(empty($_POST['category'])) {
echo 'Missing category.<br>';
$errors = true;
}
if(empty($_POST['rating'])) {
echo 'Missing rating.<br>';
$errors = true;
}
if(empty($_POST['post_name'])) {
echo 'Missing title.<br>';
$errors = true;
}
if(empty($_POST['text'])) {
echo 'Missing text.<br>';
$errors = true;
}
if($errors) {
exit;
}
// THEN ADD CODE HERE. But how display form again if user makes errors and sees nothing but error message on page if they miss something (which is how it works now)
Generally, if you find yourself repeatedly writing very similar statements, using some sort of loop is probably a better way to go about it. I think what you said about "handling and displaying the errors alongside the form" is really what you need to do if you want the process to be user-friendly. If you put your validation script at the top of the file that has your form in it, then you can just have the form submit to itself (action=""). If the submission is successful, you can redirect the user elsewhere, and if not, they will see the form again, with error messages in useful places.
if (isset($_POST['submit'])) {
// define your required fields and create an array to hold errors
$required = array('category', 'rating', 'post_name', 'text');
$errors = array();
// loop over the required fields array and verify their non-emptiness
foreach ($required as $field) {
// Use empty rather than isset here. isset only checks that the
// variable exists and is not null, so blank entries can pass.
if (empty($_POST[$field])) {
$errors[$field] = "$field is required";
}
}
if (empty($errors)) {
// insert the record; redirect to a success page (or wherever)
}
}
// Display the form, showing errors from the $errors array next to the
// corresponding inputs

Check if Youtube video valid? Code Fix

ive a database with around 5000 videos and i noticed some of them are removed now.. SO i decided to write a php script to fix bulk check this..
From the various sources below is the code i implemented based on most answers here, but it doesnt give correct results. IT gives a 403 header for 3/4th videos though practically more than 90% are working..Am i missing anything?
foreach ($video as $cat) {
$str = explode("=",$cat->videourl);
$headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $str[1]);
if (!strpos($headers[0], '200')) {
print_r($headers[0].'<br>');
$i=$i+1;
print_r("Unpublish".$cat->id. PHP_EOL);
}
else{
print_r("publish".$cat->id. PHP_EOL);
}
}
I'm printing the header here to debug it, and for most it gives, HTTP/1.0 403 Forbidden
Edit :: ive already checked the videoids are passed correctly(so string processing has no issues)
For anyone trying to achieve this, here is the code.. do appreciate if works for you as ive spend hours to get it working for the new api
$headers = checkYoutubeId ($str[1]);
if ($headers == false) {
$i=$i+1;
$db->query('UPDATE `ckf_hdflv_upload` SET `published`="0" Where `id`='.$cat->id);
print_r("Unpublished".$cat->id. PHP_EOL);
}
else{
$db->query('UPDATE `ckf_hdflv_upload` SET `published`="1" Where `id`='.$cat->id);
}
}
}
echo('done'.$i);
function checkYoutubeId($id) {
if (!$data = #file_get_contents("http://gdata.youtube.com/feeds/api/videos/".$id)) return false;
if ($data == "Video not found") return false;
if ($data == "Private video") return false;
return true;
}

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?

Statements in 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
}

Categories