Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 10/05/2021 in all areas

  1. @maviyazilim: This is the best way to handle your problem. Claiming you don't understand this code, so you can't use it, is not acceptable here. Perhaps if this was in some way complicated, you might have an argument, but this is some of the most simple and basic PHP syntax that exists, and has existed in the language since it was created. This is using "Interpolation", which is one of the features that has made PHP great to work with for web development. When using double quotes, PHP will look at the contents of a string for PHP variables, and replace those variables with their values at runtime. This code is elegant, easy to read, and far superior to the alternative of concatenating a bunch of pieces together in most situations. You should try and use it whenever you can. The link is to the PHP Manual. Look for "Complex (curly) Syntax". I will explain this to you with an example. You also need to understand PHP arrays, and in particular the way that PHP arrays can have strings as a key. Simple Interpolation: <?php $testString = 'scary ghost'; echo "She saw a $testString. It was green!" . PHP_EOL; //embed newline with \n echo "She saw a $testString. It was blue!\n"; Outputs: She saw a scary ghost. It was green! She saw a scary ghost. It was blue! Again this is one of the most basic things about PHP you should know! The $testString variable gets interpolated. In the 2nd example I use "\n" for the newline instead of the PHP_EOL constant. Interpolation of array variables is also a fundamental feature of PHP: <?php $fruit = array('apple', 'banana', 'orange', 'grape'); echo "I ate one $fruit[0] for breakfast, and one $fruit[3] for lunch\n"; Outputs: I ate one apple for breakfast, and one orange for lunch Of course PHP arrays can have programmer defined string constants for keys, and this causes a parsing problem for PHP: $name = array('first' => 'George', 'last' => 'Washington'); // Syntax error echo "The first US President was $name['first'] $name['last']\n"; The problem here is that using "$name['first']" confuses PHP, when it sees the "$var['something']" and breaks the PHP string parser. So, PHP Helpfully allows you to put curly brackets around the array, telling php to resolve the value of the array, and then interpolate it as it would with any simple variable. // Interpolating an array with a string constant key $name = array('first' => 'George', 'last' => 'Washington'); // Using complex syntax echo "The first US President was {$name['first']} {$name['last']}\n"; Output: The first US President was George Washington As in Barand's example to you, this is very useful when you are trying to create html markup. This shows concatenation, which is more complicated, and harder to see minor problems you might have, vs using interpolation, where it is very clear what the markup is that you're creating, as well as the places where variables are being injected into the string. In both cases, the output is the same html: $linkData = array('url' =>'http://www.phpfreaks.com', 'name' => 'phpFreaks'); $linkConcatenate = '<a href="' . $linkData['url'] . "'>" . $linkData['name'] . '</a>' . PHP_EOL; $linkInterpolate = "<a href='{$linkData['url']}'>{$linkData['name']}</a>\n"; echo "PHP questions answered at $linkConcatenate <br>\n"; echo "PHP questions answered at $linkInterpolate <br>\n"; Output: PHP questions answered at <a href="http://www.phpfreaks.com'>phpFreaks</a> <br> PHP questions answered at <a href='http://www.phpfreaks.com'>phpFreaks</a> <br> Yet there is more: because this also works with Object variables and methods: class Person { private $name; private $age; private $title; public $summary; public function __construct($name, $title, $age) { $this->name = $name; $this->age = $age; $this->title = $title; $this->summary = $this->__tostring(); } public function __tostring() { return "Name: {$this->name}. Age: {$this->age}. Title: {$this->title}"; } public function getName() { return $this->name; } public function getAge() { return $this->age; } } $bob = new Person('Bob Smith', 'Manager', 31); $sue = new Person('Sue Jones', 'Director', 28); echo "Bob's Summary| {$bob->summary}\n"; echo "Sue's Summary| {$sue->summary}\n"; echo " <table> <tr><th>Employee</th></tr> <tr><td>$bob</td></tr> <tr><td>$sue</td></tr> </table>"; $employees[] = $bob; $employees[] = $sue; echo "\n\n\n"; foreach ($employees as $employee) { echo "{$employee->getName()} is {$employee->getAge()} years old\n"; } Outputs: Bob's Summary| Name: Bob Smith. Age: 31. Title: Manager Sue's Summary| Name: Sue Jones. Age: 28. Title: Director <table> <tr><th>Employee</th></tr> <tr><td>Name: Bob Smith. Age: 31. Title: Manager</td></tr> <tr><td>Name: Sue Jones. Age: 28. Title: Director</td></tr> </table> Bob Smith is 31 years old Sue Jones is 28 years old Interpolation is one of the best things about PHP. I hope you take the time to learn more about how it works. You can play with all the examples I provided here if you would like to experiment: https://3v4l.org/7jUPS
    1 point
  2. Remember, people are not there to see what is actually happening or what you are doing. The solution that you get that works might be something that you don't understand, but a person who helped you who put his or her time in should at least be thanked. At least you acknowledge and thanked that in the last post that you made. I once had someone help me with a PHP script that I didn't understand and even to this day still don't after deciphering it, but it worked and there wasn't another solution out there. So I used it anyways as I spent too much time on the particular part of the script. There are a lot of times I don't understand what something does, but only to have a light-bulb go on in my head months or even years later. Object-oriented programming is something that I could do, but really never understood the meat & potatoes of it until now. It's starting to make a lot of sense now and to me that is what is fun with it comes to coding.
    1 point
  3. Using a DB, I'd do it this way (tables used are from my SQL tutorial). Select a house name and the pupils menu lists pupils from that house. <?php const HOST = 'localhost'; const USERNAME = '????'; const PASSWORD = '????'; const DATABASE = 'jointute'; // default db $db = pdoConnect(); //============================================================================== // HANDLE AJAX CALLS // if (isset($_GET['ajax'])) { if ($_GET['ajax']=='pupilopts') { exit( json_encode(pupilOptions($db, $_GET['hid']))); } exit('INVALID REQUEST'); } //============================================================================== function houseOptions($db) { $opts = "<option value=''>- select house -</option>\n"; $res = $db->query("SELECT houseID , house_name FROM house ORDER BY house_name "); foreach ($res as $r) { $opts .= "<option value='{$r['houseID']}'>{$r['house_name']}</option>\n"; } return $opts; } function pupilOptions($db, $hid) { $opts = []; $res = $db->prepare("SELECT pupilID , CONCAT(lname, ', ', fname) as name FROM pupil WHERE houseID = ? ORDER BY lname, fname "); $res->execute([$hid]); $pups = $res->fetchAll(); $opts = array_column($pups, 'name', 'pupilID'); sort($opts); return $opts; } function pdoConnect($dbname=DATABASE) { $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); return $db; } ?> <!DOCTYPE html> <html lang='en'> <head> <title>Example</title> <meta charset='utf-8'> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type='text/javascript'> $().ready( function() { $("#houses").change( function() { var hid = $(this).val() $.get( "", // specify processing file on server (in this case it's same file) {"ajax":"pupilopts", "hid":hid}, // data to send in request function(resp) { // handle the response $("#pupils").html("<option value=''> - select pupil -</option"); $.each(resp, function(k, v) { $("#pupils").append($("<option>", {"val":k, "text":v})) }) }, "JSON" // response type ) }) }) </script> <style type='text/css'> body { font-family: calibri, sans-serif; font-size: 12pt; } div { margin: 16px; padding: 8px; border: 1px solid gray; } label { display: inline-block; background-color: black; color: white; width: 120px; padding: 8px; margin: 1px 8px; } </style> </head> <body> <div> <label>House</label> <select id="houses" > <?= houseOptions($db) ?> </select> </div> <div> <label>Pupil</label> <select id="pupils" > <!-- pupil options --> </select> </div> </body> </html>
    1 point
  4. Or avoid the concatenation which is usually the biggest source of error (and the query string needs an "=") echo "<a href='icerik.php?icerik={$goster['icerik_id']}'>{$goster['baslik']}</a>";
    1 point
This leaderboard is set to New York/GMT-04:00
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.