PHP - Proper Syntax With If Statements That Have No Else?
Just curious, what is proper programming in cases where you're just doing a simple IF statement where there really is no need for an ELSE. Should you still write out the ELSE?
For example, which is proper... Code: [Select] if (x=1) { //code here to do something } or Code: [Select] if (x=1) { //code here to do something } else { } There would be nothing in the ELSE statement, so is it OK to just leave it out completely (i.e. version #1), or is it proper to still have it listed (i.e. version #2)? Similar TutorialsHi. Currently I have code the uses both TRUE. IF statements and FALSE statements to move on. For example. Is it better to use: Code: [Select] Where B=A C=A IF A=B { IF C=B{ ECHO 'HELLO WORLD'; }ELSE ECHO 'C DOES NOT EQUAL B'; }ELSE ECHO 'A DOES NOT EQUAL B'; ' OR is it better to do it like this: Code: [Select] Where B=A C=A IF A<>B { ECHO 'C DOES NOT EQUAL B'; ELSE IF C<>B{ ECHO 'C DOES NOT EQUAL B'; ELSE ECHO 'HELLO WORLD'; '[/code That's right I'm pretty green when it comes to PHP. I googled it, but it looks like there are several ways to achieve this, wondering which is best.
elseif ($subcategory_id == 400)I want the code to include a number of subcategory_ids, 400, 450, 500, 760, etc. There isn't a range, so what would be the proper way to include multiple category_ids. Thank you Hello everyone. First post here. very new to php and html. Im working on my uncles website which is a fabric store. I created a mysql database and a search to use. Im trying to make this a fulltext search because right now you have to match the pattern name exactly to get any results! And if somebody searches for the pattern name and the color they will get no results! In fact, if there is more than one search term, there is no results. -This is the first part where it counts so the pagination can be built- $sql = "SELECT COUNT(*) FROM rapatterns WHERE Pattern= '$keyword' OR Color= '$keyword' OR Fabric_Use= '$keyword'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); -here is the query to get results- $sql = "SELECT * FROM rapatterns WHERE Pattern= '$keyword' OR Color= '$keyword' OR Fabric_Use= '$keyword' LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); Ive looked into full text searching, and ive created a fulltext index on the three columns being searched here. The problem im having is when I try to change the queries to fulltext searches I get syntax errors. -this is what i was trying to do- -this is the first one that counts for pagination- $sql = "SELECT COUNT(*) FROM rapatterns WHERE MATCH(Pattern,Color,Fabric_Use) AGAINST ('$keyword') LIMIT $offset, $rowsperpage"; -here is the second one to get results- $sql = "SELECT * FROM rapatterns WHERE MATCH(Pattern,Color,Fabric_Use) AGAINST ('$keyword') LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); Im wondering if I can get a little help with the syntax or if what im trying to do wont work at all. Go easy on me. I am extremely new to any of this. I'm trying to insert an image and this is my code:
echo "<tr>"; echo '<td><input type="submit" name="btnPost" value="'.$rec['SKU'] . '"</td>' ; echo "<td>".$rec['NAME']."</td>"; echo "<td>".$rec['DESCR']."</td>"; echo "<td>".$rec['PRICE']."</td>"; echo "<td>"<img src=".$rec['IMAGE']">."</td>"; echo "</tr>"; $row++ ; I tried just echoing the .$rec['IMAGE'] without the img tag, but all it does is echo the name of the file instead of presenting the image itself. This is the code I'm using on another page in my HTML and it works fine, but I was curious how to insert the image inside my while loop. <img src="<?php echo $rec['IMAGE']; ?>"> I have been looking at this code most of the morning and do not have a clue what is wrong with the code. I am hoping its not a stupid mistake, can someone please help me out? thank you
<title>Inputing Travel Detials</title> <header> <h1 align="center"> Adding Travel Detials </h1> <body> <p> <center><img src="cyberwarfareimage1.png" alt="Squadron logo" style="width:200px;height:200px" style="middle"></center> <table border="1"> <tr> <td><a href="index.php"> Home Page </a></td> <td><a href="administratorhomepage.html">Administrator Home Page </a></td> <td><a href="viewhomepage.html">View Home Page </a></td> <td><a href="Inputhomepage.html">Input Home Page </a></td> <td><a href="traveldetials.html">Enter More Travel Detials </a></td> </table> </p> <?php include "connection.php"; $Applicant_ID = $_POST["Applicant_ID"]; $Method_Of_Travel = $_POST["Method_Of_Travel"]; $Cost = $_POST["Cost"]; $ETA = $_POST["ETA"]; $Main_Gate_Advised = $_POST["Main_Gate_Advised"]; $query = ("UPDATE `int_board_applicant` SET `Method_Of_Travel`=`$Method_Of_Travel', `Cost`=`$Cost', `ETA`='$ETA', `Main_Gate_Advised`='$Main_Gate_Advised' WHERE `Applicant_ID`='$Applicant_ID'"); $result = mysqli_query($dbhandle, $query) or die(mysqli_error($dbhandle)); if($result){ echo "Success!"; } else{ echo "Error."; } // successfully insert data into database, displays message "Successful". if($query){ echo "Successful"; } else { echo "Data not Submitted"; } //closing the connection mysqli_close($dbhandle) ?> Ok this is puzzleing. I am geting "Could not delete data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1". but its is deleting the entry that needs to be removed. The "1" is the entry. Just not sure what is causing the error. I do have another delete php but I have put that on the back burning for the time being.
<?php $con = mysqli_connect("localhost","user","password","part_inventory"); // Check connection if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { $result = mysqli_query($con, "SELECT * FROM amp20 "); $amp20ptid = $_POST['amp20ptid']; // escape variables for security $amp20ptid = mysqli_real_escape_string($con, $_POST['amp20ptid']); mysqli_query($con, "DELETE FROM amp20 WHERE amp20ptid = '$amp20ptid'"); if (!mysqli_query($con, $amp20ptid)); { die('Could not delete data: ' . mysqli_error($con)); } echo "Part has been deleted to the database!!!\n"; mysqli_close($con); } ?> Hi guys
I have this code below and all works fine when submitting this online application apart from when someone types either ' # & into one of the comment fields in which it throws up the error. Have tried various fixes from across the internet but no joy. Can anyone offer suggestions?
<?php
$con = mysql_connect("localhost:3306","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('sfapp', $con);
$sql="INSERT INTO 'sfapp' ('surname_add','forename_add','dob_add','hometele_add','mobiletele_add','homeadd_add','siblings_add','schoolname_add','headname_add','schooladd_add','schooltele_add','schoolem_add','alevel_add','personstate_add','nameprovided_add','pe_add','se_add','PredGrade_Art','PredGrade_AScience','PredGrade_BusStudies','PredGrade_Electronics','PredGrade_EnglishLang','PredGrade_EnglishLit','PredGrade_French','PredGrade_German','PredGrade_Geog','PredGrade_Graphics','PredGrade_History','PredGrade_Maths','PredGrade_SepScience','PredGrade_ProductDesign','PredGrade_Spanish','PredGrade_Other','Gender_Male','Gender_Female','Sub_EnglishLit','Sub_Maths','Sub_FurtherMaths','Sub_Biology','Sub_Chemistry','Sub_Physics','Sub_French','Sub_German','Sub_Spanish','Sub_Geography','Sub_History','Sub_RE','Sub_FineArt','Sub_Business','Sub_Computing','Sub_GlobPersp','Sub_DramaAndTheatre','Sub_PE','Sub_Dance','Sub_Politics','Sub_Psychology','Sub_Sociology','readprospect_chk','Sib_Yes','Sib_No','Current_Student_Yes','Current_Student_No','I_Understand_chk','Current_Education_chk','Local_Care_chk','Staff_Cwhls_chk','Sub_Film')
VALUES
('$_POST[surname_add]','$_POST[forename_add]','$_POST[dob_add]','$_POST[hometele_add]','$_POST[mobiletele_add]','$_POST[homeadd_add]','$_POST[siblings_add]','$_POST[schoolname_add]','$_POST[headname_add]','$_POST[schooladd_add]','$_POST[schooltele_add]','$_POST[schoolem_add]','$_POST[alevel_add]','$_POST[personstate_add]','$_POST[nameprovided_add]','$_POST[pe_add]','$_POST[se_add]','$_POST[PredGrade_Art]','$_POST[PredGrade_AScience]','$_POST[PredGrade_BusStudies]','$_POST[PredGrade_Electronics]','$_POST[PredGrade_EnglishLang]','$_POST[PredGrade_EnglishLit]','$_POST[PredGrade_French]','$_POST[PredGrade_German]','$_POST[PredGrade_Geog]','$_POST[PredGrade_Graphics]','$_POST[PredGrade_History]','$_POST[PredGrade_Maths]','$_POST[PredGrade_SepScience]','$_POST[PredGrade_ProductDesign]','$_POST[PredGrade_Spanish]','$_POST[PredGrade_Other]','$_POST[Gender_Male]','$_POST[Gender_Female]','$_POST[Sub_EnglishLit]','$_POST[Sub_Maths]','$_POST[Sub_FurtherMaths]','$_POST[Sub_Biology]','$_POST[Sub_Chemistry]','$_POST[Sub_Physics]','$_POST[Sub_French]','$_POST[Sub_German]','$_POST[Sub_Spanish]','$_POST[Sub_Geography]','$_POST[Sub_History]','$_POST[Sub_RE]','$_POST[Sub_FineArt]','$_POST[Sub_Business]','$_POST[Sub_Computing]','$_POST[Sub_GlobPersp]','$_POST[Sub_DramaAndTheatre]','$_POST[Sub_PE]','$_POST[Sub_Dance]','$_POST[Sub_Politics]','$_POST[Sub_Psychology]','$_POST[Sub_Sociology]','$_POST[readprospect_chk]','$_POST[Sib_Yes]','$_POST[Sib_No]','$_POST[Current_Student_Yes]','$_POST[Current_Student_No]','$_POST[I_Understand_chk]','$_POST[Current_Education_chk]','$_POST[Local_Care_chk]','$_POST[Staff_Cwhls_chk]','$_POST[Sub_Film]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
?>
<?php
//if "email" variable is filled out, send email
if (isset($_REQUEST['pe_add'])) {
//Email information
$admin_email = $_REQUEST['pe_add'];
$forename = $_REQUEST['forename_add'];
$email = "autoreply@testing.com";
$subject = "Application";
$desc =
"Dear $forename
Thank you for submitting your online application, we will be in touch shortly.
"
;
//send email
mail($admin_email, "$subject", "$desc", "From:" . $email);
//Email response
echo "Thank you for contacting us!";
}
//if "email" variable is not filled out, display the form
else {
?>
If you are seeing this, you need to go back and fill out the Personal Email section!
<?php
}
header("location:complete.php");
mysql_close($con)
?>
Thanks in advance.
Say I have two areas of a website. 1 - root directory (index, sign up, sign in) 2 - folders (this would contain folders such as snippets, members, assets) Due to the nature of the folders, the links cannot be the same as they are on the pages in the root directory. Index page for example. So if I'm on members/dashboard.php, any a links linking to index.php, will have to have "../" in front of them. To solve the issue, my current set up is like this. But I understand it's not the most efficient way to do this. I was wondering if you can share your expertise for a better method. $currentPage = basename($_SERVER['PHP_SELF'], ".php"); <?php if($currentPage == 'index' || $currentPage == 'members') { ?> <!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title></title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <link rel="shortcut icon" href="images/favicon.ico.png"> <link href="css/screen.css" media="screen" rel="stylesheet" /> </head> <body> <a href="index"> <img src="images/logo.PNG" alt="logo" /> </a> </body> <?php } else { ?> <!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title></title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <link rel="shortcut icon" href="../images/favicon.ico.png"> <link href="../css/screen.css" media="screen" rel="stylesheet" /> </head> <body> <a href="../index"> <img src="../images/logo.PNG" alt="logo" /> </a> </body> <?php } else { ?>
Should this be the proper way of adding the getUsername() text in the query below: Code: [Select] mysql_query("UPDATE posts SET content = '$content', lastedit = ". getUsername() .":NOW() WHERE id = '$pid'") or die(mysql_error()); Im having trouble with this wondering if someone could help me out please if (isset($_POST['escape'])) { || if (isset($_POST['suicide'])) { its giving me a error on the || im writing it so that one or the other has to happend. is this the correct way to use this? Hello everyone, I've recently asked a question about forms and Requinix mentioned PRG method of processing forms. The PRG idea solves my refresh and back button document expired problems but i notice something new: when i refresh a page or use the browser back button - then return to the PRG process - repeat a refresh or back button action - i notice that i can traverse the cache history as many times as my prg approach redirects me. I feel like i am not implementing this PRG method correctly, or is this correct? Here is the form process if it helps solve the problem: i have a login form which contains a CSRF token. when i submit the form i specify an action as /prg/ which submits the data to index.php in the prg folder. After processing the data, prg index.php redirects to the root (because you are logged in). One problem is that i have a logo on the login page that allows you to return to the root (localhost index page). When the form is not submitted or it contaiuns incorrect login data or the logo is clicked to return to homepage, then the history seems to repeat itself. I've read that people recommend to use a header 303 See Other but the result is the same. Basiclly, if i am implementing a prg correctly, then the question becomes how can i instruct a browser to ignore the redirect as if the cache contains only the index page? i cannot find prg examples that involve a csrf token and other links on the protected page (prg/index.php protected because you need a form submission with a csrf token and it only processes data then redirects.) I don't see this happening in professional sites like Google or Microsoft etc. what am i doing wrong? $sql = "SELECT option_id, id FROM bets WHERE win_status = '1' AND updated_at BETWEEN '$today 13:00:00.000000' AND '$tmrw 08:00:00.000000'"; $result = mysqli_query($connt, $sql); foreach($result as $value) { $value[] = arary_multisort(); $oid = $value['option_id']; $gid = $value['id']; var_dump($value); //$gim = var_export($value); } foreach($result as $key => $value) { $info = array($value); } mysqli_close($connt); $fl = array($oid, $gid); print_r($fl);
array ( Either I can return 1 row and have the data sorted nicely or I can return an array but I can only seem to access the last array. Been stuck on this bit for atleast 2 hrs sadly. How can I rename the array? Some days I might have 100 results. Today we have two winners xP I really need to ctrl+z sublime cuz I tried what feels like everything. Ancy to move to the next part of this code MATH if you can kindly assist. Yall have been extremely helpful in my last two posts 2/2 going on 3. Is there a place I can properly contribute lite silver :3 Code: [Select] if (isset($select_category) || isset($most_liked)) { // ALL but NO OTHER if (((($select_category == 'All') || (!isset($select_category)))) && (!isset($most_liked))) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY contribution_date DESC"; fetch_all ($dbc, $query); // CATEGORY but NOT most_liked } elseif (isset($select_category) && !isset($most_liked)) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id AND category = '$select_category' ORDER BY contribution_date DESC"; fetch_all ($dbc, $query); // CATEGORY and MOST_LIKED } elseif (($select_category != 'All') && (isset($select_category) && isset($most_liked))) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id AND category = '$select_category' ORDER BY likes DESC"; fetch_all ($dbc, $query); // ALL or NO CATEGORY but MOST LIKED } elseif ((($select_category == 'All') || (!isset($select_category))) && (isset($most_liked))) { $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY likes DESC"; fetch_all ($dbc, $query); } } What I am basically trying to accomplish is, choose a category through a drop down list, select that category and then go through all the rows in the database and print the content out. As of now it is working for me, I am also using a pagination script to print out everything in a table. The problem I am having is that fetch_all function is also printing the query out together with the content. Any ideas why it does that? Did I use this function the right way? If you need more information let me know. Hi guys, I'm starting to get back into coding for a hobby and wondering is there a better way of doing these php and mysql calls? they all work but not sure if it was the efficent way or is there others that everyone else uses?
//connection for user details lookup
while($row2 = $result2->fetch_assoc()) {
//connection for role access against business lookup
while($row3 = $result3->fetch_assoc()) { Hi Guys,
Total PHP Noob here. I’ve run into a brick-wall and would appreciate some words of wisdom. I can do this with a browser: http://86.60.161.24 // will echo hello World I can’t do this with my server: <?php $url = 'http://86.60.161.24'; $contents = file_get_contents($url); echo ($contents); ?> It looks like the server-side HTTP -request never “touches” my Arduino-chip. No network activity detected. Obviously there is going to be a lot more data transfer happening but I need to solve this issue first. Is there anything I can do to make this work? Any and all input greatly appreciated. Cheers!!
Hi.. I create mysql syntax for query testing before i input to my php code here is my mysql code: Code: [Select] set @t = 0; set @rqty=31968; SELECT LOT_CODE as code, DATE_ENTRY, CASE WHEN @t+OUTPUT_QTY > @rqty THEN @rqty -@t ELSE OUTPUT_QTY END as qty, @t := @t + d.OUTPUT_QTY as cumulative FROM dipping d WHERE SUBSTR(LOT_CODE, 9,4) = 'P28' AND (@t < @rqty); and i attach the sample output of the above query. Now that query test is work i will input that code to my php codes. $sql = "SELECT SKUCode, Materials, Comp, Qty FROM bom WHERE SKUCode = '$SKUCode'"; $res = mysql_query($sql, $con); ($row = mysql_fetch_assoc($res)); $Materials = $row['Materials']; $Qty = $row['Qty']; $Comp = $row['Comp']; //P28 //-----Compute Req Qty and Save to table---// $ReqQty = $Qty * $POReq; // 31968 $sql = "UPDATE bom SET ReqQty = '$ReqQty' WHERE SKUCode = '$SKUCode' AND Materials = '$Materials'"; $resReqQty = mysql_query($sql, $con); $t = 0; $sql = "SELECT LOT_CODE as code, DATE_ENTRY, CASE WHEN $t+OUTPUT_QTY > $ReqQty THEN $ReqQty -$t ELSE OUTPUT_QTY END as qty, $t := $t + d.OUTPUT_QTY as cumulative FROM dipping d WHERE SUBSTR(LOT_CODE, 9,4) = '$Comp' AND ($t < $ReqQty)"; when I echo the query: I got this: SELECT LOT_CODE as code, DATE_ENTRY, CASE WHEN 0+OUTPUT_QTY > 31968 THEN 31968 -0 ELSE OUTPUT_QTY END as qty, 0 := 0 + d.OUTPUT_QTY as cumulative FROM dipping d WHERE SUBSTR(LOT_CODE, 9,4) = 'P28' AND (0 < 31968) then I run it to the sql and I got an error: Error Code : 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':= 0 + d.OUTPUT_QTY as cumulative FROM dipping d WHERE SUBSTR(LOT_CODE, 9,4) = '' at line 1 (0 ms taken) Any help is highly appreciated Thank you so much Hi, I'm pretty new to php and need a bit of basic help. I have a header and footer include file in a "views" folder. The header itself has a function that's included from another directory. Now when I try to include the header in by index.php in the root it throws and error saying it can't find my function include. Obviously the include directory is relative to the file it's included in. So, what's the trick to fixing this problem? And what's the lesson for future projects? Thanx in advance. Hi All, Can any body let me know what is proper way to write below code? Quote while($row = mysql_fetch_array($result)) { for ($colq=0; $colq<=$col_no;$colq++) { while($col = mysql_fetch_array($result_display_sequences)) { for ($b=0; $b<=$seq_num;$b++) { echo $col[$b] . " "; while($asso = mysql_fetch_array($result_column_associated)) { for ($c=0; $c<=$asso_num;$c++) { echo $asso[$c] . " "; if ($col[$b] == $asso[$c]) { echo "<td>" . $row[$colq] . "</td>"; } } } } } } } I want to match two values before display the result but somehow at first level its work perfect but then its didnt increase value $b as it should. So i lil but confuse now what am i doing wrong with it. Sorry i am new and trying something hard assignment while test my skill. i do get result as below 2 2 3 4 5 6 7 8 9 10 11 3 4 5 6 7 8 9 10 11 Thanks in Advance. I am using a MVC framework and in my controller I have defined a class variable for configurations. In my action I have a call to the configuration class to set the class variable to the current configurations. Code: [Select] public $configArray = array(); public function actionBuild($id) { $this->configArray=Config::model()->getConfigArray($id); $this->buildStep1(); ... } When I echo the configuration in the method it is 10 but when I echo in buildStep1 it is 11. What is the proper way for configArray to be global and updated when I call getConfigArray for use in functions in the class? This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=345920.0 |