Php if else is not working

PHP if-else condition not working

I am facing an issue while trying to retrieve values from the if-else condition. My query is pasted below:

function filterTable($query) < $db_name = "id555865_sales_db"; $mysql_username = "id555865_sales_db"; $mysql_password = "password"; $server_name = "localhost"; $conn = mysqli_connect($server_name, $mysql_username,$mysql_password,$db_name); $filter_result = mysqli_query($conn,$query); return $filter_result; >if(isset($_POST[‘submit’]) && isset($_POST[‘fromDate’]) && isset($_POST[‘toDate’]) && isset($_POST[‘userName’]) ) < $from_date = $_POST['fromDate']; $to_date = $_POST['toDate']; $name = $_POST['userName']; if(isset($from_date) && isset($to_date) && isset($name)) < $query = "SELECT name,date,enquiry,retail,collection,booking,evaluation,test_drive,home_visit FROM employee_details WHERE date BETWEEN '$from_date' AND '$to_date' AND name LIKE'$name';"; $search_result = filterTable($query); >> elseif(empty($_POST[‘userName’]) && !empty($_POST[‘fromDate’]) && !empty($_POST[‘toDate’])) < $from_date = $_POST['fromDate']; $to_date = $_POST['toDate']; $query = "SELECT name,date,enquiry,retail,collection,booking,evaluation,test_drive,home_visit FROM employee_details WHERE date BETWEEN '$from_date' AND '$to_date';"; $search_result = filterTable($query); >elseif(!empty($_POST[‘userName’]) && empty($_POST[‘fromDate’]) && empty($_POST[‘toDate’])) < $name = $_POST['userName']; $query = "SELECT name,date,enquiry,retail,collection,booking,evaluation,test_drive,home_visit FROM employee_details WHERE name LIKE'$name';"; $search_result = filterTable($query); >else < $query = "SELECT name,date,enquiry,retail,collection,booking,evaluation,test_drive,home_visit FROM employee_details;"; $search_result = filterTable($query); >$now = time(); if (($now — $_SESSION[‘start’] > 600) && (isset($_POST[‘submit’]))) < session_destroy(); echo "Session expired.Please Login again."; header("Location:LoginPage.php"); >?> input,input[type=’text’] < border:1px solid black; padding:5px 5px; border-radius:4px; font-size:12px; >table < font-family: 'Roboto', sans-serif; font-weight:400; font-size:16px; border-collapse: collapse; width: 80%; text-align:center; margin:auto; >td, th < font-family: 'Roboto', sans-serif; font-weight:400; font-size:12px; border: 1px solid #dddddd; text-align:center; padding: 5px; >tr:nth-child(even) < background-color: #dddddd; >.headingstyle

Sales App Data

Name Date Enquiry Retail Collection Booking Evaluation Test Drive Home Visit

The problem is in the if-else part. I have a HTML form which has 3 input fields and as the user gives values in the input fields,after clicking the submit button, the data will be retrieved from the MySQL Database and shown in a table. If the user inputs data in all the 3 fields and clicks the submit button, the data is retrieved correctly from the database. But what I wanted is that if the user doesnot give any value for the «Name» field, then all the data should be retrieved according to the data value that is given. Or if the user gives value only for the «Name» field, then the data should be retrieved for only the given Name.I mentioned those conditions in the elseif part of the PHP Script,but the elseif part is never executed.It doesnot return any value.The table is empty in those cases. Can anyone please help me with this issue?

Читайте также:  HTML5 SVG logo

Источник

PHP if-then-else statement not working

My url is something such as: «inventory.php?sorting=1» and so forth. Page loads fine but does not display the information properly.

mysql_connect("localhost","user","pass"); mysql_select_db("database"); if ($sorting == 1) < $result = mysql_query("select * from vehicles ORDER BY year DSC"); >elseif ($sorting == 2) < $result = mysql_query("select * from vehicles ORDER BY make DSC"); >elseif ($sorting == 3) < $result = mysql_query("select * from vehicles ORDER BY miles DSC"); >elseif ($sorting == 4) < $result = mysql_query("select * from vehicles ORDER BY downpay DSC"); >elseif ($sorting == 5) < $result = mysql_query("select * from vehicles ORDER BY pricepay DSC"); >elseif ($sorting == 6) < $result = mysql_query("select * from vehicles ORDER BY pricecash DSC"); >else < $result = mysql_query("select * from vehicles"); >while($r=mysql_fetch_array($result)) 

Sorry, but «Page loads fine but does not display the information properly» is hardly any better than «Doesn’t want to work». Given the answers, everyone is assuming this should read «the results are not sorted as expected»?

@Justin: it’s not possible to turn off superglobals, I think it’s register_globals that you’re justly condemning.

9 Answers 9

Why not just use the field name as the GET variable?

$sortField = $_GET['sorting']; // Ensure we don't get any SQL injection: $validFields = array('year', 'make', 'miles' . 'pricecash'); $sql = "select * from vehicles"; if(in_array($sortField, $validFields)) < $sql .= ' ORDER BY ' . $sortField .' DESC'; >mysql_query($sql); 

and then access the page using inventory.php?sorting=year etc.

This makes the URL more readable, predicatable and means you can support new fields by just adding them to the array without needing to write new switch cases.

+1 for a neat solution (and for finding the problem, which is that the OP was using $sorting instead of $_GET[«sorting»] ).

-1 for SQL injection like «inventory.php?sorting=year;drop database;» See, for example, mysql_real_escape_string at php.net/manual/en/function.mysql-real-escape-string.php

sql injection won’t work in this case, because he checks that the get variable exists in an array. Unless the OP put year;drop database etc into the array.

You need to replace $sorting with $_GET[«sorting»]

Would it not be a better idea to use the switch statement?

Other solutions explain the potential of using $sorting = $_GET[«sorting»]; — but you can save code space by simple switching on the $_GET[«sorting»]; — no need to waste another var name for something that is immutable.

+1 for finding the problem and suggesting switch (@Daniel — yep, variable names are a very limited resource. Save those variables! 😉 )

I find that using $_GET[‘. ‘] can get ugly sometimes, like when you’re using get variables as indexes to arrays and have nested []’s.

I can see your point, but I think it’s alright here — I guess it depends on the situation and how many fields you’re passing in.

This is the solution I went with, thanks so much for the suggestion. I’ve never used switch before but it’s already very handy.

Short answer: Replace $sorting with $_GET[«sorting»] , or add $sorting = $_GET[‘sorting’]; to the top of your code.

Long answer: A long time ago, register_globals was used to automatically make URL parameters appear as variables. This lead to a lot of security problems (the above link contains an example), so it was eventually turned off by default (PHP 4.2.0). In PHP 6, this option no longer exists. Thus, you need to explicitly access URL GET parameters through $_GET or $_REQUEST .

As an alternative, you can explicitly import your URL parameters into local variables by using the import_request_variables command.

And to make it nicer, you can do this:

$sortBy = ''; switch($_GET["sorting"] < case 1: $sortBy = 'year'; break; case 2: $sortBy = 'make'; break; //. >if(!empty($sortBy)) < $result = mysql_query('select * from vehicles ORDER BY ' . $sortBy . ' DSC'); >else

This way, you only have to change your query at one point if you have to change it someday.

somewhere in your code? It won’t get it’s value automatically.

Add this line at the start of your code.

You need to get the $sorting variable from the $_GET array. I would also rewrite it as a switch statement like this:

Also, make sure $sorting is assigned:

$sorting = $_GET['sorting']; // Place somewhere before the switch 

you can use $_GET[‘sorting’] or $_REQUEST[‘sorting’] if it could come in by either get or post , but why not do this?

$query = "SELECT * FROM `vehicles`"; $sort_values = array( 1 => 'year', 'make', 'miles', 'downpay', 'pricepay', 'pricecash' ); $sort_number = $_GET['sorting']; if( $sort_number ` DESC"; > $result = mysql_query($query); 

note that the 1 => portion of the array is because you 1-indexed your list of queries.
the reason for the

It may not seem like it yet, but you’ll quickly find out that it’s worth it to try and find ways to write less code. Using the array means you don’t have to copy / paste any code (repeatedly writing $result = mysql_query(. ); , etc) and it is virtually effortless to add new columns to your table, should you ever need to display more information.

One might even fetch the column names from the database directly and avoid ever touching this code again.

Источник

php if/elseif not working at all

The page that calls this script allows the user to pick from 1 to 5 fields. The idea is to add up the number of fields selected and fetch the appropriate results. No matter how many fields are selected from the form the if/elseif statements do not work and I cannot see the problem. Any help would be greatly appreciated.

$sql = "SELECT * FROM my_table"; $result = $conn->query($sql); $fields_select = 0; if($country_type != "") < $fields_select = $fields_select + 1; $winearr[] = "\$country_type"; $winearr[] = "Country"; >if($region_type != "") < $fields_select = $fields_select + 1; $winearr[] = "\$region_type"; $winearr[] = "Region"; >if($wine_type != "") < $fields_select = $fields_select + 1; $winearr[] = "\$wine_type"; $winearr[] = "Type"; >if($rating_type != "") < $fields_select = $fields_select + 1; $winearr[] = "\$rating_type"; $winearr[] = "Rating"; >if($vintage_type != "") < $fields_select = $fields_select + 1; $winearr[] = "\$vintage_type"; $winearr[] = "Vintage"; >if ($result->num_rows > 0) < if ($fields_select == 0) < echo "No Results Found In Search"; >elseif ($fields_select == 1) < while($row = $result->fetch_assoc()) < if($winearr[0] == $row[$winearr[1]]) < makeListing($row); // call the function >> > elseif ($fields_select == 2) < while($row = $result->fetch_assoc()) < if($winearr[0] == $row[$winearr[1]] && $winearr[2] == $row[$winearr[3]]) < makeListing($row); // call the function >> > elseif ($fields_select == 3) < while($row = $result->fetch_assoc()) < if($winearr[0] == $row[$winearr[1]] && $winearr[2] == $row[$winearr[3]] && $winearr[4] == $row[$winearr[5]]) < makeListing($row); // call the function >> > elseif ($fields_select == 4) < while($row = $result->fetch_assoc()) < if($winearr[0] == $row[$winearr[1]] && $winearr[2] == $row[$winearr[3]] && $winearr[4] == $row[$winearr[5]] && $winearr[6] == $row[$winearr[7]]) < makeListing($row); // call the function >> > elseif ($fields_select == 5) < while($row = $result->fetch_assoc()) < if($winearr[0] == $row[$winearr[1]] && $winearr[2] == $row[$winearr[3]] && $winearr[4] == $row[$winearr[5]] && $winearr[6] == $row[$winearr[7]] && $winearr[8] == $row[$winearr[9]]) < makeListing($row); // call the function >> > > /* Debug */ echo $winearr[0]."-".$winearr[1]."-".$winearr[2]."-".$winearr[3]."-".$winearr[4]."-".$winearr[5]."-".$winearr[6]."-".$winearr[7]."-".$winearr[8]."-".$winearr[9]; echo "
\$fields_select mt24 mb12">
    phpif-statement
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
asked Oct 22, 2016 at 9:35
1
    Did you do any debug? What's the value of $fields_select?
    – u_mulder
    Oct 22, 2016 at 9:40
Add a comment|

2 Answers 2

Reset to default
0

From your code I gusset you are trying to search something by php which is not correct. Try to search by your query and let your database handle the search.

$sql = "SELECT * FROM my_table WHERE "; if($country_type != "") < $sql .= 'Country = "' . $country_type .'"'; >if($region_type != "") < $sql .= 'AND Region = "' . $region_type .'"'; >. . . $result = $conn->query($sql); if ($result->num_rows > 0) < while($row = $result->fetch_assoc()) < makeListing($row); // call the function >>

Источник

PHP If Else statement not working for database

Ok, I'm confused. I have some code that searches a database table for a username, and then uses an if else statement to run some code depending on if the user is found or not. My code is below. The problem is that the code isn't even seeing the if else statement, and I have no idea why. Any help is appreciated.

$sqluser = "select * from users where username='" . $user ."'"; //Searching to see if the user is in the database echo $sqluser . "

"; //writes out the select statement to make sure it is correct $query = mssql_query($sqluser); //returns the results $num_rows = mssql_num_rows($query); //gets the number of rows returned echo $num_rows; //writes out the number of rows if ($num_rows==0) //determines what happens next if the user exists or not < //displays an error box if the user doesn't exist echo ""; > else < //will be code to run if the user does exist echo ""; >

It is writing out $num_rows, and the query is working. Even if the query wasn't, wouldn't it have done the else portion?

Right now there are no records in the database. $num_rows is returning 0. When users are added to the database, it will return either a 0 if the username isn't found, or a 1 if the user is found. I tried if ($num_rows===0), but that didn't make any difference. I'm not sure about using count, as I'm not using an array. Also, when I viewed the page source, the script tags are showing, but for some reason the alert box isn't showing.

Источник

PHP && or if else statement not working correctly

So I have this survey that I am pulling results from and I have to basically make a bunch of if. else if. statements involving which feedback is submitted. I have set it up to work correctly. except for one problem. I know it's probably something stupid, but for the life of me I can't figure it out. Anyways here is the code.

if (($QID_A == 23) && ($row_result_2['Feedback'] == "")) < echo ""; >else if (($QID_A == 23) && ($row_result_2['Feedback'] else if (($QID_A == 23) && ($row_result_2['Feedback'] == 4) || ($row_result_2['Feedback'] == 5) || ($row_result_2['Feedback'] == 6)) < echo $row_custom['Content2']; >else if (($QID_A == 23) && ($row_result_2['Feedback'] >= 7))

The problem I am getting is if $row_result_2['Feedback'] is == to 5 or 6. It just repeats the line over and over again, basically failing to evaluate. It works fine for 4, so I am thinking my problem is somewhere in how I set up the || statements? Any help would be appreciated. Thank you. While I'm at it would there be a simpler way to write this statement? So i don't have to copy it for each QID_A field 1-50? UPDATE:: At this point I am at a loss as to why none of the below solutions are working.. I think this might be a deeper issue as the results are still repeating 24 times. Being that QID_A is 23 I think this might be related.. but I can't seem to find a connection. Thanks again for the help though guys I appreciate it. Just for the hell of it I tried writing the statements out individually. same result. for example.

if (($QID_A == 22) && ($row_result_2['Feedback'] == "")) < echo ""; >else if (($QID_A == 22) && ($row_result_2['Feedback'] else if (($QID_A == 22) && ($row_result_2['Feedback'] == 4)) < echo $row_custom['Content2']; >else if (($QID_A == 22) && ($row_result_2['Feedback'] == 5)) < echo $row_custom['Content2']; >else if (($QID_A == 22) && ($row_result_2['Feedback'] == 6)) < echo $row_custom['Content2']; >else if (($QID_A == 22) && ($row_result_2['Feedback'] >= 7))

Источник

Оцените статью