New row when displaying every new echo $row ['username'] - 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;

Related

Method to print MySQL row in PHP using foreach statement?

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

Use POST method to display data from database PHP

I am using this SQL query in a link to retrieve data from database
<div class="nav-laptop">Laptop
and display it using
$sql = $_REQUEST['upit'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='proizvodi'>";
// output data of each row
$result->data_seek(0);
while($row = $result->fetch_assoc()) {
echo "<div class='row'>";
foreach($row as $key => $value){
echo "<div class='" . $key . "'>" . $value . "</div>";
}
echo "</div>";
echo "<hr />";
}
echo "</div>";
}
else {
echo "<div class='search-query-none'><img src='index/no result.png' width='754' height='198' /></div>";
}
I realized this is very vulnerable and that I should use POST method to hide parameters from URL. I tried reading online forums, but I found nothing that would help me to convert this to POST way of retrieving data.
So, how do I use POST method to achieve the same result as I am achieving right now using GET?
This will give you a general idea on how to do this.
HTML form:
<form method="post" action="your_handler.php">
<input type = "text" name = "search_query">
<input type = "submit" name = "submit" value = "Search">
</form>
SQL/PHP and assuming a successful connection using the MySQLi API.
$conn = mysqli_connect("your_host", "user", "password", "db");
if (!$conn) {
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;
}
if(isset($_POST['submit'])){
if(!empty($_POST['search_query'])){
$search_query = mysqli_real_escape_string($conn, $_POST['search_query']);
$result = mysqli_query($conn, "SELECT * FROM TABLE WHERE col = '$search_query' ");
if(!$result) { echo "Error: " . mysqli_error($conn); }
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// perform what you want here
// and check for errors on your query
}
}
}
}
You can substitute SELECT * with the said columns also.
Ideally, a prepared statement is nice to work with.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements (if you want to look into PDO).
Sidenote: Do not intermix different MySQL APIs such as mysqli_ with PDO. They just don't mix together.
Check for errors also against your query:
http://php.net/manual/en/mysqli.error.php
Add or die(mysqli_error($conn)) to mysqli_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure that no whitespace gets introduced into your input, otherwise your query may fail.
Use trim() against the input.
You don't need to use POST for a SELECT query. You can, but it's really better suited for INSERT / UPDATE / DELETE, things that actually change your data. A possible advantage to using a link like that for search results is that it can be saved, bookmarked, emailed, etc., where a form submission cannot. But you are right that putting your entire query into a link like that definitely is extremely vulnerable.
Instead of passing the entire query through the link, you can just pass the parameters, like this:
Laptop
Then in your display code you can use a prepared statement and safely bind the parameter:
$kategorija = $_GET['kategorija'];
$sql = 'SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi
WHERE Kategorija=? ORDER BY Proizvodac';
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $kategorija);
$stmt->execute();
// etc.

Print MySQL table in PHP without knowing the columns

Im currently making a private "list management" system in which I store SQL queries in the database. So that I can via the front-end create new "lists" (which basicly are sql queries), and view them.
I have made the front end so you can save queries into the database, and im at the point where I want PHP execute and print out the results of one of my queries. This happens when I select one of my stored "lists" on my frontend. So when I press one of the lists, it should execute the SQL query. So far, so good.
But how can I, via PHP, print a table (like the one you get out from phpMyAdmin when viewing the contents of a table) without knowing how many / what columns exists? I want the script to be dynamic, so I can view results of all kinds of SELECT queries (on different tables).
Any tips or pointers?
Rather than using deprecated libraries, use PDO instead.
$db = new PDO($dsn); //$dsn is the database connection strings. Depends on your DB.
//it can be as simple as "odbc:CONN_NAME"
$stmt = $db->prepare("SELECT * FROM $tablename");
//be sure to sanitize $tablename! use a whitelist filter, not escapes!
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); //fetch as associative array
if($rows){
//check if there are actual rows!
$first_row = reset($rows); //Resets the internal pointer, return the first elem.
$header_str = '<th>' . implode('</th><th>', array_keys($first_row)) . '</th>';
$table_body_rows = array();
foreach($rows as $row){
$table_body_rows[] = '<td>' .
implode('</td><td>', $row) .
'</td>';
}
$body_str = '<tr>' . implode('</tr><tr>', $table_body_rows) . '</tr>';
$tbl = "<table><thead><tr>$header_str</tr></thead><tbody>$body_str</tbody></table>";
} else {
//something went wrong
}
show tables is probably what you need
echo "<table><tr>";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "<td> $row[0] </td>";
}
echo "</tr></table>"
mysql_free_result($result);
If you need to print a row with header (column names), you have to do it this way:
$result=mysql_query("SELECT * FROM yourtable WHERE 1");
if (mysql_num_rows($result)<1) echo "Table is empty";
else
{
$row=mysql_fetch_assoc($result);
echo "<table>";
echo "<tr>";
echo "<th>".join("</th><th>",array_keys($row))."</th>";
echo "</tr>";
while ($row)
{
echo "<tr>";
echo "<td>".join("</td><td>",$row)."</td>";
echo "</tr>";
$row=mysql_fetch_assoc($result);
}
echo "</table>";
}
This is just the basic concept. If your table has values which may contain HTML tags and other stuff, you'll need to apply htmlspecialchars() on all values of $row. This can be done with array_walk(). Furthermore you didn't mention what PHP version are you using and what MySQL API do you prefer. Some people suggested to use mysqli or PDO, that's up to you to rewrite the code according to your preferred API.

Resource id 5 error in sql

Result is returning a resource id 5 error not sure what for but i am new too this
The main issue is that my if statement is not working and i thought that was due to my result
$query = "select * from logindetails where online='1'";
$result = mysql_query($query);
echo $result;
if (mysql_num_rows($result) == 1) {
while ($row = mysql_fetch_array($result)) {
echo $row['online'] . $row['username'] . $row['password'] . $row['emailaddress'] . $row['familyname'] . $row['givenname'];
}
} else {
}
mysql_close();
?>
It's not really an error. The problem is echo $result; - You can't just print that. It doesn't know what you want to print. Also, I suggest using mysqli.
You're not really getting an error. What you're seeing is a numeric resource identifier for an external resource which in this case, is a resource in the database. Probably what you're looking for is mysql_num_rows() which will tell you the number of rows returned. You'll notice by following that link that the mysql* functions are deprecated and it's recommended that you use mysqli or PDO.
The above code outputs resource id 5 because you have given echo in the 3 line,which means your query is valid ,and the code is correct,Try giving echo mysql_num_rows($result)
Instead of echo $result, use echo $result->Row; The $result itself is an object. You want to access the Row attribute of that object.
Your if statement is only going to work if only one user is online, also. If there are more than one users online, then you are going to have more than one row, so your if statement breaks.
Try
foreach ($result as $row) {
echo $row['online'] . $row['username'] . $row['password'] . $row['emailaddress'] . $row['familyname'] . $row['givenname']. "\n";
}

php link from mysql

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)); ?>

Categories