PHP - If(!empty($variable)) And If($variable) The Same?
Is if($variable) the same as if(!empty($variable)), just different syntax?
Similar TutorialsI have this line in my code $result2 = mysqli_query($link, 'Select * from categories where cat_loc ='.$nav['id']); how do I say "if $result2 is empty or false"? (basically if it didn't find any cat_loc = to $nav['id']) to echo '</li>'; i am pulling the login date from the databases and i want it to check if the variable is empty and if it is echo Never Loged In and if it not empty echo the date <?php include'db.php'; $id=$_GET['id']; $sql=mysql_query("SELECT * FROM admin WHERE id='$id'")or die(mysql_error()); while($row=mysql_fetch_array($sql)) { $date=$row['login_date']; if($date > 0) { echo"Never Loged In"; } else { echo"$date"; } } ?> I'll try to explain this as easily as possible. I'm working on making a little link shortener site just for fun/practice as a beginner with php. I originally used the source code 'lilurl' as a base to start out, but now I'm adding stuff to it for actual practice. I need some help though. I have two files, my index and my external php file. The external file is called on at the beginning of the index with require_once. The user submits a url into the PHP_SELF form and a url is returned, and it works all great. Now I'm trying to add the option to make a custom url suffix. Code: [Select] <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <fieldset> <label for="longurl">Enter a URL:</label> <input type="text" name="longurl" id="longurl" /> <input type="text" name="suffix" id="suffix" /> <input type="submit" name="submit" id="submit" value="Shrink!" /> </fieldset> </form>[/code] The form looks like this. I added the 'suffix' textbox. So after the user submits the code, it goes back up to the top (phpself). A variable is set for the url the user has inputted as "$longurl", like this. Code: [Select] $longurl = trim(mysql_escape_string($_POST['longurl']));So I added this. Code: [Select] $suffix = ($_POST['suffix']);And to check if it worked, I went down the the bottom of the index and had it echo the suffix variable. When I entered in code into the suffix text box, it would be echoed at the bottom of the page, so the variable did receive the value. So here's where the external file comes in. It is called on by require_once at the very beginning of the index. It is full of functions. One of the functions generates a random string of numbers (that I coded) to be used as the url suffix (uses the $id variable). So my plan was to erase the $id = $rand1 . blah blah stuff and put $id = $suffix. $suffix being the variable from the index that the user inputted. Make sense? Well whenever I try it, it always acts the like the variable is empty, even when I echo it on the index it returns the value of the textbox. Does anyone know what I'm doing wrong? Could it be because since I call on $suffix in the external file, and it's only been declared in the index that it's treating it like a new/empty variable? [spoiler] Someone also explained it to me like this. -I call upon the external file. -I declare the variable is the value of the text box. (Which means it's currently empty because the form has not been submitted.) -Then, the form is submitted as PHP_SELF. -The external file is called upon again. -The variable is then assigned a value. It's hard to explain, but basically that the variable in the external file is not told about the new value of the variable because they are declared after the external file is called upon? :\ So I tried moving the $suffix = ($_POST['suffix']); before the external file is called upon, but the same thing happens. It's hard to explain the situation, but I've tried a lot of things and can't get it to work.[/spoiler] Hello all, I am a beginner at PHP and trying to form an IF statement, I'm running into a problem which I cannot seem to solve. Due to my lack of syntax knowledge I would appreciate if someone could point me in the right direction. The combo variables are sent to this page through a form and defined as these variables at the top of the page. e.g $combo0 = $_POST["combo0"]; When the results are displayed any form field which was left blank or empty I want to show "N/A" if data is detected in being sent through the form I then want the "Else" statement to take affect. Currently when I run the below statement N/A is echoed despite if data was sent through the form fields or not.... if (empty($scrap)) { echo "<h3>Submitted Scrap Results</h3> No scrap parts were booked off"; } elseif (empty($combo0) || empty($combo1) || empty($combo2) || empty($combo3) || empty($combo4)) { echo "N/A"; } else { echo "<h3>Submitted Scrap Results</h3> <b>Reason:</b> " .$combo0." - ".$combo1." - ".$combo2." - ".$combo3." - ".$combo4." <br /> <b>on machine</b> " .$mid. " - <b>No. Scrap</b> " .$noscrap. ""; } Anyone any ideas? I know the following simple demonstration fails and what to do to rectify it (though with a lot of additional code is necessary), but I don't know why this is the behaviour. It would be great if someone could explain to me why, and what the neatest way of fixing it would be. Code: [Select] +----------+--------------+------+-----+---------+ | Field | Type | Null | Key | Default | +----------+--------------+------+-----+---------+ | Id | int(11) | NO | PRI | NULL | | Name | varchar(45) | YES | | NULL | | Number | int(9) | YES | | NULL | Code: [Select] $name = "Bradley Cooper"; $number = ""; $query = "INSERT INTO table (Id, Name, Number) VALUES (1, '$name', $number)"; mysql_query($query); Because the $number variable is empty, this simple query fails. Logically, one would think that nothing or NULL gets inserted to that field since the MySQL structure rule states that default is NULL, and since nothing is fed to it in the query, I think that it would automatically be NULL since if the column is omitted, that is exactly the value that will be inserted. Enclosing the variable with quotes is not preferable since this field accepts integers. Also, converting the variable to an integer by (int)$number results in a 0, which is not what I want either. Checking if the variable is empty of not, and if it is, assign $number = "''" so that the query would succeed by enclosing the empty string with single quotes. But this creates a lot of unnecessary code (some of my tables are 80 columns wide and the query therefore have equal amount of variables). So to summarise, why is this happening and how do I neatly avoid assigning quotes to the empty strings? In other words, how do I insert nothing when variables that usually contain an integer is on occation empty? How would I write this in php?: Code: [Select] If $url does not begin with 'http://' $url = '' I want to assign nothing to the variable if it doesn't begin with http:// Thanks! I am trying to allow the user to update a variable he chooses by radio buttons, which they will then input text into a box, and submit, to change some attributes. I really need some help here. It works just fine until I add the second layer of variables on top of it, and I can't find the answer to this question anywhere. <?PHP require('connect.php'); ?> <form action ='' method='post'> <select name="id"> <?php $extract = mysql_query("SELECT * FROM cars"); while($row=mysql_fetch_assoc($extract)){ $id = $row['id']; $make= $row['make']; $model= $row['model']; $year= $row['year']; $color= $row['color']; echo "<option value=$id>$color $year $make $model</option> ";}?> </select> Which attribute would you like to change?<br /> <input type="radio" name="getchanged" value="make"/>Make<br /> <input type="radio" name="getchanged" value="model"/>Model<br /> <input type="radio" name="getchanged" value="year" />Year<br /> <input type="radio" name="getchanged" value="color" />Color<br /><br /> <br /><input type='text' value='' name='tochange'> <input type='submit' value='Change' name='submit'> </form> //This is where I need help... <?PHP if(isset($_POST['submit'])&&($_POST['tochange'])){ mysql_query(" UPDATE cars SET '$_POST[getchanged]'='$_POST[tochange]' where id = '$_POST[id]' ");}?> Hello all. I am very new to PHP, and I am not sure where to look or what I'm looking for in my current assignment. My task is to take in two numbers between 0-100. Once I take in that number, it should state beside it "The __ was accepted." The program should not accept any numbers greater than 100 or any characters. Once I do this, I must take a second number and do a similar thing. Finally, I must have a statement show up at the bottom stating which number is greater. Essentially, I need help in determining what I should use to place parameters, and how I can keep the program from echo ing any statement until input has been taken and tested for parameters. Any help you can provide will be greatly appreciated! I have just re-installed Xampp and suddenly my sites are now displaying lots of: Notice: Use of undefined constant name - assumed 'name' in ... Notice: Use of undefined constant price - assumed 'price' in ... this is an example of the line its refering too: $defineProducts[1001] = array(name=>'This is a product', price=>123); My login script stores the user's login name as $_SESSION[ 'name'] on login. For some unapparent reason, i'm getting errors stating that $user and $priv are undefined variables, though I've attempted to define $user as being equal to $_SESSION['name'], using $user to look up the the user's privilege level (stored as the su column ) in the SQL table, and then where the result of the sql query is $priv which is then evaluated in an if statement. I can't seem to figure out why this might not be working. The code I'm using: <?php session_start(); function verify() { //verify that the user is logged in via the login page. Session_start has already been called. if (!isset($_SESSION['loggedin'])) { header('Location: /index.html'); exit; } //if user is logged in, we then lookup necessary privleges. $_SESSION['name'] was written with the login name upon login. Privleges // are written in db as a single-digit integer of of 0 for users, 1 for administrators, and 2 for special users. $user === $_SESSION['name']; //Connect to Databse $link = mysqli_connect("127.0.0.1", "database user", "password", "database"); if (!$link) { echo "Error: Unable to connect to MySQL." . PHP_EOL; echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } //SQL Statement to lookup privlege information. if ($result = mysqli_query($link, "SELECT su FROM accounts WHERE username = $user", MYSQLI_STORE_RESULT)) { //LOOP TO CYCLE THROUGH SQL RESULTS AND STORE Privlege information as vairable $priv. while ($row = $result->fetch_assoc()) { $priv === $row["su"]; } } // close SQL connection. mysqli_close($link); // Verify privleges and take action. Only a privlege of "1" is allowed to view this page. A privlege of "2" indicates special //accounts used in other scripts that have certain indermediate additional functions, but are not trusted administrators. if ($priv !== 1) { echo $_SESSION['name']; echo "you have privlege level of $priv"; echo "<br>"; echo 'Your account does not have the privleges necessary to view this page'; exit; } } verify(); ?>
I have a form that creates rows of data input textboxes depending on a user input number of things. I have a naming convention for all these textboxes that basically just keeps incrementing a number suffix for each row. All this is working fine. My problem is I need to get the data inserted into this table of textboxes into an array. Here's my code where I attempt to to this (it does not work): Code: [Select] $temp = $_SESSION['Num_Part']; $count = 1; while ($count <= $temp){ $temp2[$count] = "'Participant_P".$count."'"; //echo $temp2[$count]."<br/>"; $temp3[$count]=$_POST[$temp2[$count]]; //here's the problem $temp4[$count] = "'Result_P".$count."'"; $temp5[$count]=$_POST[$temp4[$count]]; //here's the problem //echo $temp4[$count]."<br/>"; $count++; } The problem is that the $_POST does not work with the variable in the argument position - even though the argument is formatted with single quotes. Can a variable be used in a POST argument and if so what is the correct syntax? If not, is there some other simple solution to harvest the data into an array. I understand I can harvest by explicitly accessing each key in the post assoc array. But this could be dozens of rows of input fields. Thanks in advance for your help here. I couldn't find anything online re this topic. I have a script that adds points together based upon the placing. This is the actual script: Code: [Select] <? $points = 0; if($place === '1st') {$points = $points + 50;} elseif($place === '2nd') {$points = $points + 45;} elseif($place === '3rd') {$points = $points + 40;} elseif($place === '4th') {$points = $points + 35;} elseif($place === '5th') {$points = $points + 30;} elseif($place === '6th') {$points = $points + 25;} elseif($place === '7th') {$points = $points + 20;} elseif($place === '8th') {$points = $points + 10;} elseif($place === '9th') {$points = $points + 10;} elseif($place === '10th') {$points = $points + 10;} elseif($place === 'CH') {$points = $points + 50;} elseif($place === 'RCH') {$points = $points + 40;} elseif($place === 'TT') {$points = $points + 30;} elseif($place === 'T5') {$points = $points + 30;} elseif($place === 'Champion') {$points = $points + 50;} elseif($place === 'Reserve Champion') {$points = $points + 40;} echo "Total HF Points: $points"; ?>What it *should* do (my friend's script works the same way and it works) it starts at points = 0, than if there is a first place, it adds 50, and so forth until it reaches the end. It is included into a file, in this area: Code: [Select] <div class="tabbertab"> <h2>Records</h2> <? $query92 = "SELECT * FROM THISTABLE WHERE VARIABLE='$id' OR VARIABLE = '$name' ORDER BY ABS(VARIABLE), VARIABLE"; $result92 = mysql_query($query92) or die (mysql_error()); echo "<table class='record'> <tr><th>Show</th> <th>Class</th> <th>Place</th></tr> "; while($row92 = mysql_fetch_array($result92)) { $class = $row92['class']; $place = $row92['place']; $entries = $row92['entries']; $race = $row92['show']; $purse = number_format($row92['purse'],2); echo "<tr><td>$race</td> <td>$class</td> <td>$place</td></tr>"; } ?> <tr><td colspan='3'><div align='right'><? include('includes/points.php'); ?></div></td></tr> </table> </div> This is the code that is relevant. When ended here, it echoes the last place that appears in the results (such as a 5th place echoing 30 points). When I move it to be included in the while loop, it shows Total Points: 50 Total Points: 25 Total Points: 10 (depending on the results displayed on that page). What am I doing wrong? Hello everyone, I can get Test 2 to successfully operate the if statement using a variable variable. But when I try the same method using a session variable (Test 1) the if statement is not executed. Please could you tell me why the if statement in Test 1 is not being executed? Code: [Select] <?php # TEST 1 $_SESSION[test_variable] = "abcd"; $session_variable_name = "_SESSION[test_variable]"; if ($$session_variable_name == "abcd") { echo "<br>line 373, abcd<br>"; } # TEST 2 $test_variable = "efgh"; $test_variable_name = "test_variable"; if ($$test_variable_name == "efgh") { echo "<br>line 379, efgh<br>"; } ?> Many thanks, Stu hi all, I have an language pack for example: languages/en.php: Code: [Select] $en['mail']['letter closing'] = "regards,\n your friend!"; and in my config: Code: [Select] $language = "en"; $include_language = @include("languages/".$language.".php"); if(!($include_language)) { $try_default_language = @include("languages/nl.php"); if(!($try_default_language)) { echo "kan de taalpakket niet vinden<br>"; echo "Could not find the language pack.<br>"; echo "example on error: ".$test." shows nothing"; exit; } } In my function I want to include the language pack for example i have $language = 'en' so I want to include $en['general']['letter closing'] I will do this: Code: [Select] global $language,${$language}['general']; But that gives an error unexpected '[' blah blah. How can i call the variable variable array in the valid php way? I just moved my code from Appserv to EasyPHP and it gave me this error, it was working fine on Appserv...what's with easyPHP ?? Probably something simple but I have searched high and low and can't figure this one out. I have a variable that is of the datetime format. I have another variable that is of the time format. I need to add them together. Example: $var1 = 2012-02-24 06:38:22 $var2 = 02:00:00 $var3 = $var1 + $var2 = 2012-02-24 08:38:22 Thanks for the help! I have a function that get's a quick single item from a query: function gimme($sql) { global $mysqli; global $mytable; global $sid; $query = "SELECT ".$sql." FROM ".$mytable." WHERE sid = ".$sid; $result = $mysqli->query($query); $value = $result->fetch_array(MYSQLI_NUM); $$sql = is_array($value) ? $value[0] : ""; return $$sql; // this is what I've tried so far $result->close(); } It works great as: echo(gimme("name")); Then I realized that I could use that as a variable ('$name' in this case) elsewhere. However, I can't figure out how get that new, variable variable 'outside' of the function. As such, echo($name); isn't working outside the function. Is there a way to return a variable variable? In other words, is there a way to make a function that creates a variable variable that will available outside of the function?
Thanks
Quote i need to store a variable from database like if i have "copies" in one of my column in my database then i have to store a particular value for copies store it to $copies here i want that i can store value of copies into $copies $update_book="update book set copies=copies-1 where bookid='$bookid'"; $result=mysql_query($update_book,$linkID1); if($result) { print "<html><body background=\"header.jpg\"> <p>book successfully subtracted from database</p></body></html>"; } else { print "<html><body background=\"header.jpg\"> <p>problem occured</p></body></html>"; } } Hi, so I have an easy problem that for some reason I couldn't find an answer to anywhere. I have a bunch of variables like this: $pic1fileName $pic2fileName $pic3fileName $pic4fileName $pic5fileName...you get the idea So I have another variable I'm pulling from a database that specifies which number to show, so I need a variable something like this: $pic($pic_number)fileName I just don't know what the proper syntax is. Anyone? Thank you freaking much for any help; this is a lame problem. So I'm fairly new to php and just need some quick help. Here is my code: Code: [Select] function plaintext_category(){ $cat_plain = strip_tags( get_the_term_list($post->ID, 'portfolio_category', '', ', ', '' ) ); $cat_plain = strtolower($cat_plain); $cat_plain = str_replace(' ','-',$cat_plain); echo $cat_plain; } $pattern = '/title=\"(.*?)\"/'; $replace = 'title="echo $cat_plain"'; /* This is where i need help, how do i echo this? */ $categories = preg_replace($pattern,$replace,$categories); echo $categories; So I'm trying to pass the echo value of $cat_plain but when I put echo in front of it, i get an error. If I don't put echo, I just get a blank result. Please, need some help on this. Thanks guys! |