PHP - Strange Behavior With Ternary Operator
Hey all,
when job_title property is equal to null, I want this to happen: Welcome to the blog of John Merlino. If it is not null then: Welcome to the blog of John Merlino, a web designer. //where web designer refers to the value stored in job_title So I come up with this: Code: [Select] echo "Welcome to the blog of " . $blogger->first_name . ' ' . $blogger->last_name . (!is_null($blogger->job_title)) ? ', ' . $blogger->job_title . '.' : '.'; But when job_title is null, all the page renders is this: Code: [Select] , . That's right. Just a comma, then a space, and then a period. What am I missing here? Thanks for response. Similar Tutorialshello i keep seeing Ternary Operators like this Code: [Select] $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; but how would i turn this if statement in to a Ternary Operator ? Code: [Select] if($a == $b){ echo 'hello'; }else{ //do nothing } thanks I'm returning a table row that contains information about a file, but it seems in IE versions older than 10, it is cutting off some of the returned json when being used.
The data is being returned properly as seen in the following json:
{"file_name":"<i class='video'><\/i> <a href=\"\/Development\/test(4).mp4\" class=\"is_file\" target=\"_blank\">test(4).mp4<\/a>"}But when you use it, it cuts off the html. A simple alert will return </i> test(4).mp4</a>and same when appending it and the sort. It is also happening for another part of HTML that is being returned properly in the json. It is working for everything else that is returned. I have been searching around for a very long time trying to find why this is happening. Has anyone other than me encountered this? So i am currently coding database connection class and i have encountered very strange behavior from my script. base.class.php: Code: [Select] <?php class base{ private $settings; function get_settings(){ $settings["dbhost"] = 'localhost'; $settings["dbuser"] = '*****'; $settings["dbpass"] = '*****'; $settings["dbname"] = 'core'; return $settings; } } ?> database.class.php Code: [Select] <?php require_once 'base.class.php'; class database extends base{ private $query_now; private $link; public function __construct(){ $settings = base::get_settings(); $dbhost = $settings["dbhost"]; $dbuser = $settings["dbuser"]; $dbpass = $settings["dbpass"]; $dbname = $settings["dbname"]; $this->link = mysql_connect($dbhost, $dbname, $dbpass) or die ("Could not connect to the mysql database"); mysql_select_db($dbname, $this->link) or die ("Could not select the database"); } function query($query){ $this->query_now = $query; return mysql_query($query, $this->link); } function getArray($result){ return mysql_fetch_array($result); } } ?> When i try to create an instance of database class, i get mysql_connect error. I have tried to echo my array and it seems that correct information is being passed over. Now the strange thing is if i remove my password from the base class i don't get a mysql_connect error but this time instead i get "Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'core'@'localhost' (using password: YES) " In case you are wondering, does my mysql database user has a password, the answer is: yes for sure... (Also i have tried to setup a simple script for connecting to my database and everything worked fine) So any ideas? Current time when testing was: 1291064453 I run the following: echo date('m/d/y', strtotime('first day', 1291064453)); Expecting: 11/1/10 What I actually get: 11/30/10 Can anyone explain this? Hi guys, In my connection.php I have: $db->query("DROP TABLE IF EXISTS mydata") ; $db->query("CREATE TABLE mydata ( ID INT AUTO_INCREMENT NOT NULL PRIMARY KEY, guid INT, title VARCHAR(100), body LONGTEXT, term VARCHAR(100) )"); and my query code : $myarray = array ( guid => 100, title => "title test", body => "just a test", term => "term test", ); $myplaceholders[] = '(' . implode (", ", array_fill(0, count($myarray), '?')) . ')'; //also tried '(?,?,?,?)' $mykeys = implode(', ', array_keys($myarray)); array_push($values, ...array_values($myarray)); //also tried $values = array_values($myarray) ; $res = $db->prepare("INSERT INTO mydata ($mykeys) VALUES " . join(', ', $myplaceholders)) ; if ($res->execute($values)) { echo 'data inserted'; } else { echo 'error in query'; } After executing the code, the table is created but no data is inserted. The strange thing is when I leave the create table statement out of the connection.php and run the code the data is inserted. Any ideas where I'm going wrong? I am working with the Amazon API, and I am trying to display a default image if a product does not have an image associated with it. The query is coming back as an array. Typically, each product image array looks like this: $d = SimpleXMLElement Object ( http:// => [url]http://ecx.images-amazon.com/images/I/51aUIul6XjL._SL160_.jpg [Height] => 160 [Width] => 112 ) The code goes like this: Code: [Select] if ($d=$E->MediumImage) { $iu=$d->URL; $ih=$d->Height; $iw=$d->Width; echo count($d); if (strlen($iu) > 0) {echo "<center><a href='$url' target='_blank'><img src='images/amazon_noimage.jpg' width='175' height='175' border='0'></a></center>";} else {echo "<center><a href='$url' target='_blank'><img src='$iu' width='$iw' height='$ih' border='0'></a></center>";} } However, images/amazon_noimage.jpg never shows up (even though it is linked correctly, as I've tested this link). I have tried the following: if (strlen($iu) > 0) if (count($iu) > 0) if (strlen($d->URL) > 0) if (count($d->URL) > 0) if (isset($d)) if (!isset($d)) etc ... If I display the following, where there is no image, I get nothing displayed: echo $iu; print_r($iu); echo $d->URL; etc ... However, if there is an image, I get a link, such as the following: http://ecx.images-amazon.com/images/I/51c2BFpDN0L._SL160_.jpg There seems to be NOTHING that I can do to trigger the 'ELSE' part of the if statement. This is a total enigma to me ... any ideas?? This topic has been moved to HTML Help. http://www.phpfreaks.com/forums/index.php?topic=331683.0 Ok so I have a simple database table set up, and I am trying to get the results into an HTML table, however I have a question. One loop I write in a for loop will dump the data I want to the table, the other returns no results. For example I have the code... Code: [Select] //SQL Lookup //SQL Lookup $sqlAppt = mysql_query("SELECT * FROM Appointment WHERE TTUNumber = \"$TTUNumber\" && ShippingNumber = \"$ShippingNumber\" LIMIT 1") or die('Could not execute SQL statement ' . mysql_error()); $numbRows = mysql_num_rows($sqlAppt); echo "<p>Number of rows found: $numbRows </p>\n"; So When I create the first whlile loop, i do not get any results from my database. Code: [Select] while($r=mysql_fetch_array($sqlAppt)){ $ApptDate=$r['Date']; $ApptTime=$r['Time']; $ApptNumber=$r['ApptNumber']; $ApptDock=$r['Dock']; echo '<h1>I got here</h1>'."\n"; echo "<table>\n"; echo "<tr><td>Date</td><td>$ApptDate</td></tr>\n"; echo "<tr><td>Time</td><td>$ApptTime</td></tr>\n"; echo "<tr><td>Appt Number</td><td>$ApptNumber</td></tr>\n"; echo "<tr><td>Dock</td><td>$ApptDock</td></tr>\n"; echo "</table>\n"; } The Results is this: Quote Number of rows found: 1 I got here Date Time Appt Number Dock However, when I create a different loop structure... Code: [Select] for($i = 0; $i < $numbRows; $i++) { $r=mysql_fetch_array($sqlAppt); $ApptDate=$r['Date']; $ApptTime=$r['Time']; $ApptNumber=$r['ApptNumber']; $ApptDock=$r['Dock']; echo '<h1>I got here</h1>'."\n"; echo "<table>\n"; echo "<tr><td>i:</td><td>$i</td></tr>\n"; echo "<tr><td>Date</td><td>$ApptDate</td></tr>\n"; echo "<tr><td>Time</td><td>$ApptTime</td></tr>\n"; echo "<tr><td>Appt Number</td><td>$ApptNumber</td></tr>\n"; echo "<tr><td>Dock</td><td>$ApptDock</td></tr>\n"; echo "</table>\n"; } Naturally I get a different result! Quote Number of rows found: 1 I got here i: 0 Date 1982-12-26 Time 08:00:00 Appt Number 123 Dock 34 I can't figure out why for the life of me that my while loop would not return anything on here>? Does anyone have any idea's? Thanks hello; my webhost made a change to my php.ini file yesterday. since then php is escaping single quotes that it receives from flash. Code: [Select] //-- AS3 var myVariables:URLVariables = new URLVariables(); myVariables.pvs_params = "'h'e'l'l'o" ; var myURLRequest:URLRequest = new URLRequest("mysql_task_mgr.php"); myURLRequest.data = myVariables ; myURLRequest.method = "get" ; navigateToURL( myURLRequest, '_blank' ) ; Code: [Select] //-- php print( $_GET[ "pvs_params" ] ) ; // --> \'h\'e\'l\'l\'o any thoughts? my webhost is stumped; I'm trying to have a running total of the number of views an image gets. My test file works perfectly every time. The actual file, image_win.php, does not and after much testing can't see what's wrong. This files STRANGENESS: the first two views count fine, with 1 added the total in the field image_visit. But every time after that 2 is added to the total in image_visit. Very bizarre. Thanks for taking a look -Allen Code: [Select] <?php ////////TEST IMAGE_WIN //////////THIS WORKS include_once "scripts/connect_to_mysql.php"; include_once "scripts/paths.php"; $art_id = 372; $QUERY="SELECT user_id FROM artWork WHERE art_id = '$art_id'"; $res = mysql_query($QUERY); $num = mysql_num_rows($res); if($num >0){ while($row = mysql_fetch_array($res)){ $owner_id = $row['user_id']; } } mysql_query("UPDATE userInfo SET image_visit = image_visit +1 WHERE user_id = '$owner_id'"); ?> <?php //////// image_win.php /////////THIS DOES NOT WORK $user_id=$_SESSION['user_id']; include_once "scripts/connect_to_mysql.php"; include_once "scripts/paths.php"; $image_link = $_GET['image_link']; $art_id = $_GET['art_id']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, height=device-height, target-densityDpi=device-dpi"> <title>Image Window</title> </head> <body bgcolor="#000000" leftmargin="0"> <div align="center" > <img src="slir/w640-h535/<?php echo $path.$image_link.$postCat; ?>" /> <?php $QUERY="SELECT user_id FROM artWork WHERE art_id = '$art_id'"; $res = mysql_query($QUERY); $num = mysql_num_rows($res); if($num >0){ while($row = mysql_fetch_array($res)){ $owner_id = $row['user_id']; } } mysql_query("UPDATE userInfo SET image_visit = (image_visit +1) WHERE user_id = '$owner_id' "); ?> MOD EDIT: code tags added. I'm having trouble understanding the behavior of Prefix decrementing operator VS. Postfix decrementing Operator Postfix decrementing Operator Code: [Select] <?php $a = 1; $a = --$a + 1; echo $a; // this outputs 1 ?> VS.... Prefix decrementing operator Code: [Select] <?php $a = 1; $a = $a-- + 1; echo $a; // this outputs 2 ?> if($AClass->select_error || $BClass->ErrorFile){ include("/path/to/files/".($AClass->select_error ? 'no_selector' : 'error_file_missing').".php"); exit; } if($CClass->WriteError){ include("/path/to/files/FileWriteError.php"); exit; } Probably a simple one for you folks, but I can't for the life of me work out how to make the above into 1 line of ternarys. Cheers, Rw In this statement... $firstName = (isset($_SESSION['memberFirstName']) ? $_SESSION['memberFirstName'] : ''); Can isset() be replaced with most other functions, e.g. empty(), is_numeric(), is_null(), etc?? Thanks, Debbie I have just discovered ternary conditionals and really like the time and space saving, they seem pretty simple and look neater than a bunch of if else statements crammed together. The thing I would like to know is what is the best or correct method of usng the following; $page = isset($_GET['page']) ? $_GET['page'] : '1'; or do I need the extra parentheses like below; $page = (isset($_GET['page'])) ? $_GET['page'] : '1'; I understand that if I used a second conditon I would need the extra parentheses e.g $page = (isset($_GET['page']) && is_numeric($_GET[page'])) ? $_GET['page'] : '1'; Thanks! Please bear with me in the following exercise. I'm fairly new to php (but not coding) and am trying to push my skills for the future, so I'm going beyond a problem for which I already have a solution to see if I understand the coding principles correctly. I am trying to understand just how far I can push the ternary operator shorthand. I know how to do simple tasks, but I'm wondering if I can perform more than one command in the same statement? I'm a little confused because I'd like to both set a session variable and do a page redirect and I have a feeling that the order of these operations matters, so all I've done here may be incorrect. I have a form on the front page of my site that includes a checkbox that is required in order to enter the site. The form action goes to a page where this is checked, a $_SESSION variable is set, and the page is redirected. I am also not sure if I need the session_write_close(); command, or if it is in the right place. In the full length version, it could be moved into the set of commands following the IF. Here is the full length code that I would like to translate into shorthand: Code: [Select] <?php session_start(); if (isset($_POST['ConsentCheckbox']) { $_SESSION['Consented'] = 'true'; header('Location: http://www.mySite/welcome'); } else { header('Location: http://www.mySite/errors/NotConsented'); } session_write_close(); ?> The if/else conditions translate easily into these two lines of code, which could be one line if I didn't also need to set the session variable: Code: [Select] <?php session_start(); $_SESSION['Consented'] = isset($_POST['ConsentCheckbox']) ? 'true' : 'false'; header('Location: http://mySite.com/'.($_SESSION['Consented'] ? 'welcome' : 'error/NotConsented')); session_write_close(); ?> But, I really only need to set the $_SESSION variable if the $_POST['ConsentCheckbox'] is set. This makes the test on the following pages of my site much simpler (where I test to see if the $_SESSION variable is set and then either redirect to the consent form or load the desired page). SO, I'm wondering if it can be further condensed. I've come up with these possibilities, but am not totally sure. This has now become a theoretical exercise in coding for me. Here is what I think is possible, but I have a couple of outstanding questions, so I'd like some input, please. I first translated it into the following. I think this is correct, although I'm not sure if I need brackets around the multiple commands in the TRUE section. Code: [Select] <?php session_start(); isset($_POST['ConsentCheckbox']) ? $_SESSION['Consented']='true'; header('Location: http://www.mySite.com/welcome') : header('Location: http://www.mySite/errors/NotConsented'); session_write_close(); ?> Then, I wondered if I can even further condense it in the following way? Here is where the order of the commands is likely to break the code - and I'm not entirely sure that my use of double quotes will suffice instead of escaping out the end bracket of the header() command: Code: [Select] <?php session_start(); header('Location: http://www.mySite.com/'.(isset($_Post['ConsentCheckbox']) ? "welcome')"; $_SESSION['Consented'] = 'true' : "errors/NotConsented')"); session_write_close(); ?> Have I gone too far? Thanks Hi, This ones stumped me a little as i've done this previously and it seemed to work fine: I have a form to add with two password boxes, the IDs are different as they should be but the type is the same: Code: [Select] <form action="<?php echo $PHP_SELF;?>" method="post"> <p>New Password: <input type="password" id="newpassword" name="newpassword" /></p><br /> <p>Confirm Password: <input type="password" id="confirmpassword" name="confirmpassword" /></p><br /> <p><input type="submit" name="submit" value="submit"></p> </form> I have this code to check if they are both equal then md5 them and add them to the database: Code: [Select] // Check if button name "submit" is active, do this if(isset($_POST['submit'])) { //variable to identify user $email = ($_SESSION['email']); //post variable from form $newpassword = $_POST['newpassword']; $password = $_POST['confirmpassword']; //if passwords are not equal if($password != $confirmpassword) { echo "The passwords do not match<br />"; //debugging - to see if they are equal or not - remove afterwards echo $password . "<br />"; echo $newpassword . "<br />"; } //if passwords are equal if($newpassword == $password) { //use md5 so they match when logging in $password = md5($password); $newpassword = md5($newpassword); $sql= "UPDATE users SET password='$newpassword' WHERE username='$email'"; $result = mysql_query($sql); if($result) { echo "Congratulations You have successfully changed your password"; } } } I've tried to explain my thinking as best i can in the code, the debugging part at the top shows that both values seem to be identical yet i'm being thrown into the not equal loop and they aren't adding to the database. Can anyone explain what i'm doing wrong here? I imagine its only minor but its thrown me. Cheers I've been looking through the Joomla docs trying to understand how everything works and I've seen something that I don't understand and cannot find an answer to anywhere on the net. The basic question is what is the ampersand used for in this conditional he if (!($mask & 1) && is_string($var)) { The two in the middle are obviously the AND part of the conditional. I know it can be used for creating references to variables but I don't think this is what is happening here. I've seen people using it to test for odd and even numbers too but with no explanation of how it works/what it does. The full code is below: function _cleanVar($var, $mask = 0, $type=null) { // Static input filters for specific settings static $noHtmlFilter = null; static $safeHtmlFilter = null; // If the no trim flag is not set, trim the variable if (!($mask & 1) && is_string($var)) { $var = trim($var); } // Now we handle input filtering if ($mask & 2) { // If the allow raw flag is set, do not modify the variable $var = $var; } elseif ($mask & 4) { // If the allow html flag is set, apply a safe html filter to the variable if (is_null($safeHtmlFilter)) { $safeHtmlFilter = & JFilterInput::getInstance(null, null, 1, 1); } $var = $safeHtmlFilter->clean($var, $type); } else { // Since no allow flags were set, we will apply the most strict filter to the variable if (is_null($noHtmlFilter)) { $noHtmlFilter = & JFilterInput::getInstance(/* $tags, $attr, $tag_method, $attr_method, $xss_auto */); } $var = $noHtmlFilter->clean($var, $type); } return $var; } Hi Ok, so I pick a random value 23 for example and I want this value to be in between two other values. E.g. if 23 is in between 20 and 30, then continue otherwise die. How can I do this? I see a couple people using the ? operator in php and was curious as to how it works? |