Variables in braces - PHP coding question - php

This is my PHP/MySQL script:
<?php
mysql_connect('localhost', 'root', 'test') or die (mysql_error());
mysql_select_db('info1') or die (mysql_error());
$result = mysql_query("SELECT * from automobiles");
//Table starting tag and header cells
while($row = mysql_fetch_array($result)){
//Display the results in different cells
echo "<dd><dl><img src=' " . $row['image'] . " '>" . $row['manufacturer'] ." " . $row['model'] . "</dd></dl>";
echo "<dd><dl>" . $row['carinfo'] . "</dd></dl>";
}
//Table closing tag
echo "</table>";
?>
However, would it work if I did it this way:
{$myvariable}
Is it a good idea to code the variables with the braces, or as:
echo " . $row['variable']. "
Any help is appreciated, thanks!

You can do this:
echo "<dd><dl>{$row['carinfo']}</dd></dl>";
You cannot do this:
echo "<dd><dl>$row['carinfo']</dd></dl>";
This also wont work:
echo '<dd><dl>{$row['carinfo']}</dd></dl>';
Your output would actually be:
<dd><dl>{$row[ SOME PHP ERROR
This is due to using single quotes instead of double quotes. And the error would be because you did not escape the single quotes inside the variable.
If you did this:
echo '<dd><dl>{$row["carinfo"]}</dd></dl>';
Your output would actually be:
<dd><dl>{$row["carinfo"]}</dd></dl>
For the same single quote vs double quote reasoning.

I personally prefer using the " " . $row['variable']. " " syntax because it's easier to read code, specially if you have a code syntax highlighter. But using this syntax is acceptable: "{$var['field']}".

Related

How to add Microdata attributes in PHP

I use Microdata attributes in HTML code.
How can I add Microdata attributes to the following tag (PHP)?
if (!empty($speciality)) {
echo "<p><strong>" . __('Speciality', 'framework') . "</strong><span>" . $speciality . "</span></p>";}
The page will not load when I enter the following way :
echo "<p itemscope itemtype="https://schema.org/medicalSpecialty"><strong>" . __('Speciality', 'framework') . "</strong><span itemprop="medicalSpecialty" >" . $speciality . "</span></p>";
you are using double quotes in a double quotes which is wrong, use backslash or single quote when you need.
Try This code
echo "<p itemscope itemtype='https://schema.org/medicalSpecialty'><strong>" . __('Speciality', 'framework') . "</strong><span itemprop='medicalSpecialty' >" . $speciality . "</span></p>";
You're mixing single and double quotes but you need to reserve either single or double quotes to escape the string so that your PHP isn't read as HTML when echoed. The below snippet will work without any errors:
if (!empty($speciality)) {
echo "<p itemscope itemtype='https://schema.org/medicalSpecialty'><strong>'".
__('Speciality', 'framework') . "'</strong><span itemprop='medicalSpecialty'
>'" . $speciality . "'</span></p>";
}

HTML in PHP - displaying variables from MYSQL table

I have a MYSQL table containing tournament data for players. Each player has stats like games_won, games_lost, etc. I am trying to display this information in a table.
My PHP code looks like this:
//Connecting to $db
//...
//Store table data into array
$result = mysqli_query($db, "SELECT * FROM ladder");
while($row = mysqli_fetch_array($result)) {
echo $row['id'] . " " . <a href=$row['link']$row['username']</a> . " " . $row['tourney_wins'] . " " . $row['game_wins'] . " " . $row['game_losses'] . " " . $row['last_played'];
echo "<br>";
I get an error (Unexpected "<") on
<a href=$row['link']$row['username']</a>
I am trying to display each username in the table as a hyperlink to their respective profile on another site. Can anyone give me a correction? Thanks!
This is how it should be quoted (assuming I interpreted how you wanted the link properly):
//Connecting to $db
//...
//Store table data into array
$result = mysqli_query($db, "SELECT * FROM ladder");
while($row = mysqli_fetch_array($result))
{
echo( $row['id']." <a href='".$row['link']."'>".$row['username']."</a> ".$row['tourney_wins']." ".$row['game_wins']." ".$row['game_losses']." ".$row['last_played'] );
echo("<br>");
}
Change
<a href=$row['link']$row['username']</a>
to
"<a href=$row['link']$row['username']</a>"
You forgot to quote your html:
echo $row['id'] . " " . <a href=$row['link']$row['username']</a> . " " ...snip...
^--here ^--here
Since it's not quoted, PHP is interpreting it <a as concatenate less than undefined constant 'a', which makes no sense.

php echo no output to display very puzzled, why?

I am getting no where with this, I am not getting any output from my echo ,can someone help, thanks in advance...singhy
code below...
$strSQL = "SELECT * FROM <tablename> WHERE id='" . $_GET["serviceName"] . "'";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)){
echo "<dt>Name:</dt><dd>" . $row["serviceType"] . " " . $row["serviceName"] . "</dd>";
echo "<dt>Phone:</dt><dd>" . $row["Phone"] . "</dd>";
echo "<dt>Birthdate:</dt><dd>" . $row["BirthDate"] . "</dd>";
}
// Close the database connection
mysql_close();
?>
<p>Return to the list</p>
</body>
</html>
can someone tell me where i am going wrong, ive tried various options, thanks in advance, singhy
Try this debugging code:
$serviceName = mysql_real_escape_string($_GET['serviceName']); // Read PS note at the end
$strSQL = "SELECT * FROM `tablename` WHERE id='$serviceName'";
$rs = mysql_query($strSQL) or die(mysql_error()); // Display any query error
echo "Total number of rows: ". mysql_num_rows($rs); // Echo number of rows
while($row = mysql_fetch_assoc($rs)){
echo "<dt>Name:</dt><dd>" . $row["serviceType"] . " " . $row["serviceName"] . "</dd>";
echo "<dt>Phone:</dt><dd>" . $row["Phone"] . "</dd>";
echo "<dt>Birthdate:</dt><dd>" . $row["BirthDate"] . "</dd>";
}
Please note
You should escape the $_GET request and never use it directly in a query statement. Use mysql_real_escape_string() for that. (This method will be deprecated, read next bullet)
many of the functions you are using will be deprecated starting php 5.5.0 Alternatively you can use PDO prepared statements
replace
$_GET["serviceName"]
with this
$_GET['serviceName']
use single quotes in $_GET in your case.

How to create a series of DIVs using PHP + mySQL?

I'm looking to create a formatted product list from an SQL database. My aim is to have a store on my website with a series of small boxes containing some shorthand information about each product, that when clicked will open a pop-up containing detailed information. (I have a working Javascript/JQuery code to create the pop-ups.)
Here is the PHP code so far, simply to get the information from the database and display it on a webpage...
(I've been using XAMPP to provide an environment for me to test the code in)
<?php
mysql_connect("localhost", "root", "") or die (mysql_error ());
mysql_select_db("Database1") or die(mysql_error());
$strSQL = "SELECT * FROM Products";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
echo $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "<br />";
}
mysql_close();
?>
I want the echoed line to be displayed in a divider, with a divider generated for each record in the SQL database (say I have 10 products available, there would be ten dividers, and 10 different boxes on the webpage). The divider's class is "ProductBox".
echo "<div class=\"ProductBox\">"; $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
This was the closest I have come to a solution, which was simply managing to write a code with no syntax errors - alas, nothing actually displays on the webpage.
If I'm going about this entirely the wrong way please tell me - I'm fairly sure I need to use a SQL database to dynamically update stock on a live website, but if I need to implement a different programming language or whatever then just tell me what you think would work and help me with a solution.
You have an extra semicolon in your code
echo "<div class=\"ProductBox\">"; $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
Replace with
echo "<div class=\"ProductBox\">". $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
mysql_fetch_array needs to be used like this (see PHP Doc):
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
}
or you could just use "mysql_fetch_assoc" instead.
HOWEVER, if you're new to PHP, I HIGHLY RECOMMEND that you get started on the right foot. mysql_query functions are soon to be deprecated. DON'T USE THEM. Most recommend using "PDO" for querying your database. Here's a great tutorial to teach you: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Also, as mentioned, you have an extra semi-colon.
Dont forget these basics markups :
`<HTML>
<HEAD>
</HEAD>
<BODY> put in here your divs
</BODY>
</HTML>`

PHP having syntax problems with quotations wrapped around a variable in PHP embedded in HTML

This appears right to me but it is incorrect (code hint coloring around '{$row["type"]}' is wrong wrong -- from the color it is in my IDE it's been considering a string, and it's throwing an error when i run it in the browser). I've spent hours trying to figure this out on my own to no avail. Any help would be greatly appreciated.
echo "<select selected = '{$row["type"]}' name='expense[" . $id . "][type]' >" . $type_options . "</select>";
When using arrays in strings, you can't use quotes. Just skip them.
echo "<select selected = '{$row[type]}' name='expense[" . $id . "][type]' >" . $type_options . "</select>";
Your quotes arren't right.
echo '<select selected ="'.$row["type"].'" name="expense['.$id.'][type]">'.$type_options.'</select>';
You currently have a problem with unescaped double quotes terminating your string. My suggestion would be to use the more standard double-quotes for your HTML element properties, and use single quotes to delineate your strings, with variable concatenated. Liek this:
echo '<select selected = "' . {$row["type"]} . '" name="expense[' . $id . '][type]">' . $type_options . '</select>';
or for even better readability, use printf
$format = '<select selected = "%s" name="expense[%d][type]">%s</select>';
printf($format, $row['type'], $id, $type_options);
$type_options = "options";
echo $type_options;
Have you not tried this?
echo "This works: {$row['type']}";
Your code wont work because you have an empty string before you echo your variable.
echo "#EMPTY STRING HERE!" . $type_options . "#EMPTY STRING HERE!";
Why are you doing that?
Use this
echo $type_options;
Or even this if you want content in your string
echo "Content" . $type_options . "Content";

Categories