I am revisiting php and mySQL from a long time off.
mysql_select_db($database_conn, $conn);
$query = sprintf("SELECT DISTINCT Username FROM Entries ");
$result = mysql_query($query);
$row_results = mysql_fetch_assoc($result);
<?php do {
//$name = $row_results['Username'];
//echo $name, "<br/>";
echo '<a href=\"$row_results['Username'],.php\">';
echo '$row_results['Username'],'s overview </a><br/>';
}
while ($row_results = mysql_fetch_assoc($result)); ?>
What I am trying to do is echo out the link from the results the link is in the form username.php the username is stored in the database.
I have used single quotes and double quotes with escaped /" in but get different errors I know its going to be something as simple as a ; or " .
If you could be as kind to explane what is wrong abd if there is a better way to do this?
The query is correct and the commented out code also works on its own.
Thanks
You cannot parse variables through single quotes:
echo '<a href=\"$row_results['Username'],.php\">';
use
echo '<a href="'.$row_results['Username'].'">';
mysql_select_db($database_conn, $conn);
$query = sprintf("SELECT DISTINCT Username FROM Entries ");
$result = mysql_query($query);
$row_results = mysql_fetch_assoc($result);
<?php do {
//$name = $row_results['Username'];
//echo $name, "<br/>";
echo '<a href="'.$row_results['Username'].'php">';
echo $row_results['Username'].'\'s overview </a><br/>';
}
while ($row_results = mysql_fetch_assoc($result)); ?>
Looks to me like the concatenation of your html string and the username is incorrect.
Currently, your string that you are writing to the page is
<a href=\"$row_results['Username'],.php\">
What you need to be doing is joining the html with the value coming out from the database.
This can be done like so:
echo '<a href=\"'.$row_results['Username'].'.php\">';
echo $row_results['Username'].'\'s overview </a><br/>';
Notice the '.' to concatenate two potions of the string, and the escapement of the apostrophe in the 's
Here are your errors :
Even though you are using DISTINCT in your SQL Query, there might be multiple entries, so you must use a while loop.
You had a comma in there (probably by typo).
You need to escaping the php variable.
So after doing the above, this is what it should be.
while ($row_results = mysql_fetch_assoc($result)) {
echo '<a href="' .$row_results["Username"]. '.php">';
}
try:
echo '<a href="'.$row_results['Username'].'.php">';
echo $row_results['Username'].'\'s overview </a><br/>';
Seems like you got pretty mixed up with the " and ' there. You should really avoid using anything other than ' - it will only bite you on the long run.
Also: You concatenate with ., not with ,.
mysql_select_db($database_conn, $conn);
$query = sprintf('SELECT DISTINCT Username FROM Entries ');
$result = mysql_query($query);
$row_results = mysql_fetch_assoc($result);
do {
$name = $row_results['Username'];
echo $name.'<br/>';
echo '<a href="'.$name.'.php">';
echo $name.'\'s overview </a><br/>';
} while ($row_results = mysql_fetch_assoc($result)); ?>
Related
I am new to PHP and programming, but am attempting to print out the results from each row of one of my MySQL database tables.
Using a set of while loops I achieved this:
while($placeHolder = $query->fetch_assoc()){ // use assoc
echo "<div class='placeHolder'><img src=" . $placeHolder['photo']. " /></div>";
echo "<br />";
}
while($placeHolder2 = $query2->fetch_assoc()){
echo "<div class='placeHolder2'>" . $placeHolder2['name'] . "</div>";
echo "<br />";
}
//etc, etc...
Besides being inefficient, I'm assuming this may also be a security risk.
Is there a better way to do this, possibly using a foreach statement?
Here is my SQL code I forgot to include:
$query = mysqli_query($conx, $sql);
$query2 = mysqli_query($conx, $sql);
$sql = ('SELECT id,name,picture FROM table ORDER BY name DESC LIMIT 50');
I dont think using a foreach statement to print out the results would make it any less safe/unsafe. It really depends on your query. You should be able to print all of them using a foreach doing something like:
$result = $query->fetch_all(MYSQLI_ASSOC);
foreach($result as $row) {
echo $row['photo'];
}
Note** to use fetch_all you would need mysqlnd installed
edit: looking at your query nothing can be injected there. No outside variables being used in the query, so its safe. I would just use the while loop that you originally posted.
edit 2: link to fetch_all documentation: http://php.net/manual/en/mysqli-result.fetch-all.php
I really don't know how to explain this question. But, I'm trying to make a product page that shows the same row as it is currently showing (so example "go onto a tech product page and at the bottom it shows all other tech related products").
Here is what I've tried:
<?php
$pType = $row['typeP'];
$sql = "SELECT * FROM products WHERE type=$pType";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while ($row = mysqli_fetch_array($result)){
echo "<a href='products.php?id={$row['productID']}'>";
echo "<img src='uploads/{$row['displayIMG']}'>";
echo "</a>";
}
?>
Your error would be in the $typeP declaration. I am guessing $row is not defined before that. therefor it is empty. Maybe you were trying to use a GET?
<?php
$pType = $_GET['typeP']; //This would get the type id from the querystring
$sql = "SELECT * FROM products WHERE type='".$pType."'";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while ($row = mysqli_fetch_array($result)){
echo "<a href='products.php?id=".$row['productID']."'>";
echo "<img src='uploads/".$row['displayIMG']."'>";
echo "</a>";
}
?>
I should also mention that your code is subject to SQL injection. Please clean your inputs before running them through you database. Otherwise you are asking for trouble.
http://www.wikihow.com/Prevent-SQL-Injection-in-PHP
I want if is possible to display the username in a new row instead of one next to the other.
e.g.:
admin
user1
user2
admin
user1
user2
Here is my code:
$con = mysql_connect('localhost','root','');
mysql_select_db('chatbox',$con);
$sql = "SELECT `username`
FROM `users`
ORDER BY `username` ASC";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_array($result))
{
echo $row['username']; //over here
}
?>
Use either
echo $row['username'] . "<br>" . "\n";
or
echo $row['username'] . "<br>" . PHP_EOL;
which will produce both clean HTML and new lines on screen for each word/name.
Sidenote: It's important to use double quotes for the \n. If not and using single quotes such as '\n' will echo n which is not what you want. Therefore, use "\n".
Nota: \n and PHP_EOL will only produce new lines/carriage returns in HTML source and not on screen, which I believe is what the ultimate goal is.
Plus, if used when writing files, will place them on seperate lines.
Therefore, you need to add <br> for your purpose.
Footnotes:
mysql_* functions are deprecated and will be removed from future PHP releases.
Use mysqli with prepared statements, or PDO with prepared statements,
they're much safer.
You should use the following as your while loop:
while($row = mysql_fetch_array($result))
{
echo $row['username'], "<br/>", PHP_EOL;//over here
}
PHP_EOL specifies a platform independent new line character.
Note: mysql function is deprecated since PHP 5.5, so you have to move to mysqli function.
If you want to use foreach approachment, then it should be like this:
<?php
$row = mysql_fetch_array($result);
foreach($row as $key => $value) echo $row['username'].PHP_EOL;
How do i do it? I'v tried all different ways but I just cant do it!
Basically, im trying to pull out information from the "starters table" and display only the logged in users data.
Here is the code which gives me an error message in which I cannot solve:
<?php
session_start();
require_once '../database.php';
if (isset($_SESSION['myusername'])){
echo "Welcome ".$_SESSION['myusername'];
}
?>
<?php
include '../database.php';
$userid = $_SESSION["myusername"];
#the where clause is where im stuck at the moment!
Line 50:
$result = mysql_query("SELECT Recipename, Ingredients, Method, Time FROM starters WHERE username = $_SESSION['myusername']");
echo "<table border='0'><table border width=65%> <tr><th>Recipie Name</th><th>Ingredients</th><th>Method</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Recipename']. "</td>";
echo "<td>" . $row['Ingredients']. "</td>";
echo "<td>" . $row['Method']. "</td>";
echo "<td>" . $row['Time']. 'minutes'."</td>";
echo "</tr>";
}
echo "</table>";
?>
</table>
the error message i get is the following:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/jahedhus/public_html/cook/usersloggedin/starters.php on line 50
line 50 is the select statement!
I would really appreciate your help,
Thanks so much!
You need to wrap the username in quotes:
$result = mysql_query("SELECT Recipename, Ingredients, Method, Time FROM starters WHERE username = '{$_SESSION['myusername']}'");
Additionally, you're trusting that $_SESSION['myusername'] is a valid username (not some string of attach SQL). If you don't know that data is safe, you need to at least escape the data.
Change the line:
$result = mysql_query("SELECT Recipename, Ingredients, Method, Time FROM starters WHERE username = $_SESSION['myusername']");
with this one:
$result = mysql_query("SELECT Recipename, Ingredients, Method, Time FROM starters WHERE username = '" . $_SESSION['myusername'] . "'");
Problem with the quotes is that they will get all gummed up, i'd seperate them either:
$result = mysql_query("SELECT Recipename, Ingredients, Method, Time FROM starters WHERE username = ".$_SESSION['myusername']);
OR
$result = mysql_query("SELECT Recipename, Ingredients, Method, Time FROM starters WHERE username = '$_SESSION[myusername]'");
Sorry for this question to be a "can you fix it" one, but this little bit of code has been confusing me for a while now.
I'm basically making a table with a bunch of rows and columns and in each one I have a slightly changing SQL query. To make it a bit easier instead of typing all that out I made this bit of script but it is starting to get a bit complicated so can any of you manage to get it correct?
echo '<td background="images/map/';
$tile = mysql_fetch_array(mysql_query("SELECT image FROM map WHERE horizontal = ${'mapPiece' . $mapPieceCount . [0]} AND verticle = ${'mapPiece' . $mapPieceCount . [0]}"));
echo $tile[0];
echo '.png"></td>';
Thanks, Stanni
Assuming I interpreted this right, the [0] needs to go outside of the curly braces:
echo '<td background="images/map/';
$tile = mysql_fetch_array(
mysql_query(
"SELECT image FROM map WHERE horizontal = ".
${'mapPiece' . $mapPieceCount}[0].
" AND verticle = ".
${'mapPiece' . $mapPieceCount}[0]
)
);
echo $tile[0];
echo '.png"></td>';
First of all, you can't append the array index [0] like that, like you're concatenating on a string. Overall, it would be much easier if you just added a few extra lines to make things neater:
$currentPiece = 'mapPiece' . $mapPieceCount;
echo '<td background="images/map/';
$query = 'SELECT image '.
'FROM map '.
'WHERE horizontal = '.${$currentPiece}[0].' '.
'AND verticle = '.${$currentPiece}[0];
$result = mysql_query($query);
$tile = mysql_fetch_array($result);
echo $tile[0];
echo '.png"></td>';