How to assign a span to a certain username - php

A Solution has been found! Thank you to #northkildonan and #Doug Leary.
Solution Code;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<li class='list-group-item'>" . $row["user_name"];
if ($row["user_name"] == "TacoLover22") {
echo "<span class='badge'>Dev</span>";
}
echo "</li>";
}
##
I have a list of usernames and I have a code that checks if a username exists, if it does exist, I want a div to be appended to it. Here's an image explaining this
However, the code I have works, but it doesn't assign that div to the selected username.
Here's the PHP Code;
<?php
if (
$row["user_name"] === "TacoLover22");{
echo "<span class='badge'>Dev</span>";
}
?>
here's the other php code that grabs all the usernames;
<?php
$servername = "####";
$username = "####";
$password = "########";
$dbname = "########";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT user_name FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<li class='list-group-item'>" . $row["user_name"];
}
} else {
echo "0 results";
}
$conn->close();
?>
The result of this code can be found here.
EDIT: Here's the full code from suggestions, it still doesn't seem to work. The span doesn't appear now.
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<li class='list-group-item'>" . $row["user_name"];
if ($row["user_name"] === "TacoLover22") {
echo "<span class='badge'>Dev</span>";
}
echo "</li>";
}
Thanks for all and any help.

I think this will do it:
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<li class='list-group-item'>" . $row["user_name"];
if ($row["user_name"] === "TacoLover22") {
echo "<span class='badge'>Dev</span>";
}
echo "</li>";
}

you have to append the <span> inside your mysql-fetch-loop (note: you are talking about divs, but you are using a span, which is something different in html).
while($row = $result->fetch_assoc()) {
echo "<li class='list-group-item'>" . $row["user_name"];
if ($row["user_name"] == "TacoLover22")
{
echo "<span class='badge'>Dev</span>";
}
}
explanation: you are iterating the resultset of your mysql-query right in your while-loop. the variable $row is your pointer which points to the respective row of your result.
after your while-loop is finished, your "pointer" will always show to the last result row of your mysql-query. so $row["user_name"] will always be set to the last user name found in your database. that's why you have to access it inside the while-loop.
how to handle multiple users (as requested):
I decided to use switch instead of if elseif statements here since it's better to read and less to write imho:
while($row = $result->fetch_assoc()) {
echo "<li class='list-group-item'>" . $row["user_name"];
switch($row["user_name"])
{
case "TacoLover22":
echo "<span class='badge'>Dev</span>";
break;
case "AnotherUser":
echo "<span class='badge'>User</span>";
break;
}
}

assuming u are using sqli extention
the column user_username is list of special users, otherwise you will need 2 tables, 1 table to store users, and 1 auxiliar table to store special users
//query
$sql = "SELECT user_name FROM users";
//send to mysql, get result
$sendquery = $conn->query($sql);
//fetch results as array
while ($result=$sendquery->fetch_array) {
echo 'username:' . $result['user_name'] . '<span class='badge'>Dev</span>';
}
but your question is confusing, you should use 2 tables if you are having different type of users
TABLE USERS user_id | name | dev_id | email | password | ...
TABLE DEVS dev_id | name | level | access | ....
SQL query, using LEFT JOIN
SELECT
usern.name as username, dev.name as devname
FROM USERS as user
LEFT JOIN DEVS as dev
USING dev_id
php output use $result['devname']
$result['']
if you only neeed "TacoLover22" to display, in case thats the only person you need to add something, add a IF in the while cycle
//query
$sql = "SELECT user_name FROM users";
//send to mysql, get result
$sendquery = $conn->query($sql);
//fetch results as array
while ($result=$sendquery->fetch_array) {
if ($result['user_name'] == "TacoLover22") {
echo 'username:' . $result['user_name'] . '<span class='badge'>Dev</span>';
}
else {
echo $result['user_name'];
}
}

Related

PHP Displaying Name from Database to page

I'm trying to pull data from my database like their First name and Last name and make it display on my webpage. This is my php inside of my html markup.
<?php
if (isset($_SESSION['userId'])) {
require './includes/dbh.inc.php';
$result = mysqli_query($conn,"SELECT * FROM users");
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<li class='login current2'><a href='login.php'>". $row['fnidusers'] . $row['lnidusers'] ."</a></li>";
}
}
}
else {
echo "<li class='login current2'><a href='login.php'>Login / Sign up</a></li>";
}
?>
I'm attempting to make a drop down with their name as the label for it. For example:
Amazon has similar drop down that I'm looking for, It says the name of the user.
Thanks for the help.
If you want to display only the current logged in user, you can do it with your request like this :
"SELECT * FROM users WHERE user_id = '" . $_SESSION['userId'] . "'"
Here you are searching in all rows, the one with id the current logged in user id.
Now, just reuse the var in your while but without the while :
$row = $result->fetch_assoc();
Now your code will look something like this :
<?php
require './includes/dbh.inc.php';
if (isset($_SESSION['userId'])) {
$resut = mysqli_query($conn, "SELECT * FROM users WHERE user_id = '" . $_SESSION['userId'] . "'");
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo "<li class='login current2'><a href='login.php'>". $row['fnidusers'] . $row['lnidusers'] ."</a></li>";
}
} else
echo "<li class='login current2'><a href='login.php'>Login / Sign up</a></li>";
?>
Please excuse my bad english ^^

PHP and MySQL WP

I am trying to accomplish two things here with this code. I am writing PHP directly into a WP page using the INSERT PHP Plugin.
1) Query the MySQL database and return the results from one column into four columns.
2) Make each result is its own hyperlink that directs the user to a new WP page that runs a new query on that page.
I am able to get the query to show results and even to turn those results into a dynamic hyperlink, however I cannot get the formatting down. Right now it just returns the result into one column. Here is what I have:
[insert_php]
$servername = "localhost";
$username = "login"; //edited for privacy
$password = "password"; //edited for privacy
$database = "database"; //edited for privacy
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//get results from database
$result = mysqli_query($conn,"SELECT mine FROM mines ORDER BY mine");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo "<td><a href='urlhere/$row[$item]'>".$row[$item]. "</a>"."</td>"; //get items using property value
}
echo '</tr>';
}
echo "</table>";
[/insert_php]
Thanks for any help you can offer.
I'd like the results to look like this (each one as a hyperlink):
Image link below
I was able to work this out. Still have not gotten the results to properly hyperlink but the array is filling in over four columns now. Here is my code:
$sql = "SELECT mine FROM mines ORDER by mine";
$result = mysqli_query($conn, $sql);
if ($result) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row['mine'];
}
}
if (is_array($data) && count($data)) { // if array's not empty, create HTML
//create a table & header row
$htmlout="<table><tr>
<th colspan='4'>Mine</th></tr>
<tr>
";
$counter = 1; //keep count of data
foreach ($data as $mines) {
//table cell for datum
$htmlout .= "<td>$mines</td>\n";
//rows of 4
if ($counter % 4 == 0) {
$htmlout .= "</tr>\n<tr>\n";
}
$counter++;
}
}
$htmlout .= "</tr></table>";
echo $htmlout;

How to make a PHP page have two "column" regions?

Basically I'm doing digital signage and I'm trying to get names to be pulled from a MySQL database to a PHP page. Right now its all centered in one column, but I want the results to be in two columns side by side. How can I do this?
$sql = "SELECT * FROM donor WHERE DonationAmount = 5000 AND Category = '1' or DonationAmount = 5000 AND Category IS NULL ORDER BY LastName ASC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName']. "<br>";
}
else{
echo $row["LastName"]. ", " . $row["FirstName"]. "<br>";
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "<br>";
}
}
} else {
}
Basically I want this data to be spread across two columns instead of 1 single page.
output the strings like this:
echo "<span style=\"width:50%;float:left;\">".$row['LastName']."</span>";
do not forget to remove <br /> from each output
You can use tables, and count the rows to determine if you need to start a new table row.
$i = 0;
$total_rows = $result->num_rows;
echo "<table><tr>";
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
echo "<td>";
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName'];
}
else{
echo $row["LastName"]. ", " . $row["FirstName"];
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "";
}
echo "</td>";
$i++;
if($i % 2 == 0 && $i != $total_rows) {
echo "</tr><tr>";
}
}
echo "</tr></table>";
if your content is in <div id="myDiv"> use this JS function and call it after the content loads
function splitValues() {
var output = "";
var names = document.getElementById('myDiv').innerHTML.split("<br>");
for(var i in names) {
output += "<span style=\"width:50%;float:left;display:inline-block;text-align:center;\">"+names[i]+"</span>";
}
document.getElementById('myDiv').innerHTML = output;
}

If 0 items in DB table, return error

I am looking for a way to display an error message if there is nothing listed in the table.
I have a photos table.
If this tables is empty, id like to echo something.
else, show the pictures.
inside of that table I have
id, name, url
id = id
name = name of image
url = url of image.
If there are no rows, we have an error.
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
mysql_fetch_array($query1);
if(empty($query1)) {
echo "nothing";
} else {
echo "good";
}
Try this,
$query = "SELECT * FROM photos";
$result= mysql_query($query);
$length= mysql_num_rows($result);
if($length>0)
{
while($rows = mysql_fetch_array($result))
{
echo $rows['name'];
echo "<img src='$rows[url]' />";
}
}
else
{
echo "Nothing to display";
}
Hope this will work
What about something like...
$sql = "SELECT COUNT(*) AS amountPhotos FROM photos";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row["amountPhotos"] == 0) {
echo "There are no photos in the photo table.";
}
or
$sql = "SELECT * FROM photos LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "There are no photos in the photo table.";
}
Try this
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
$result = mysql_fetch_array($query1);
if(empty($result)) {
echo "nothing";
} else {
echo "good";
}
This pretty much sums up the answer for this question: http://www.w3schools.com/php/php_mysql_select.asp
They even provided a sample code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //<--- here they check if number of rows returned is greater than 0 (so there is data to display)
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results"; //<----- nothing found
}
$conn->close();
?>
Just modify this and you'll be good to go.

Displaying all records in a mysql table

The code below works fine for printing one record from a database table, but what I really want to be able to do is print all the records in the mysql table in a format similar to my code.
I.E.: Field Name as heading for each column in the html table and the entry below the heading. Hope this is making sense to someone ;)
$raw = mysql_query("SELECT * FROM tbl_gas_meters");
$allresults = mysql_fetch_array($raw);
$field = mysql_query("SELECT * FROM tbl_gas_meters");
$num_fields = mysql_num_fields($raw);
$num_rows = mysql_num_rows($raw);
$i = 1;
print "<table border=1>\n";
while ($i < $num_fields)
{
echo "<tr>";
echo "<b><td>" . mysql_field_name($field, $i) . "</td></b>";
//echo ": ";
echo '<td><font color ="red">' . $allresults[$i] . '</font></td>';
$i++;
echo "</tr>";
//echo "<br>";
}
print "</table>";
Just as an additional piece of information you should probably be using PDO. It has more features and is helpful in learning how to prepare SQL statements. It will also serve you much better if you ever write more complicated code.
http://www.php.net/manual/en/intro.pdo.php
This example uses objects rather then arrays. Doesn't necessarily matter, but it uses less characters so I like it. Difference do present themselves when you get deeper into objects, but not in this example.
//connection information
$user = "your_mysql_user";
$pass = "your_mysql_user_pass";
$dbh = new PDO('mysql:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
//prepare statement to query table
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
//loop over all table rows and fetch them as an object
while($result = $sth->fetch(PDO::FETCH_OBJ))
{
//print out the fruits name in this case.
print $result->name;
print("\n");
print $result->colour;
print("\n");
}
You probably also want to look into prepared statements. This helps against injection. Injection is bad for security reasons. Here is the page for that.
http://www.php.net/manual/en/pdostatement.bindparam.php
You probably should look into sanitizing your user input as well. Just a heads up and unrelated to your current situation.
Also to get all the field names with PDO try this
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
Once you have all the table fields it would be pretty easy using <div> or even a <table> to arrange them as you like using a <th>
Happy learning PHP. It is fun.
Thanks guys, got it.
$table = 'tbl_gas_meters';
$result = MYSQL_QUERY("SELECT * FROM {$table}");
$fields_num = MYSQL_NUM_FIELDS($result);
ECHO "<h1>Table: {$table}</h1>";
ECHO "<table border='1'><tr>";
// printing table headers
FOR($i=0; $i<$fields_num; $i++)
{
$field = MYSQL_FETCH_FIELD($result);
ECHO "<td>{$field->name}</td>";
}
ECHO "</tr>\n";
// printing table rows
WHILE($row = MYSQL_FETCH_ROW($result))
{
ECHO "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
FOREACH($row AS $cell)
ECHO "<td>$cell</td>";
ECHO "</tr>\n";
}
while ( $row = mysql_fetch_array($field) ) {
echo $row['fieldname'];
//stuff
}
Try this :
$raw = mysql_query("SELECT * FROM tbl_gas_meters");
$allresults = mysql_fetch_array($raw);
$field = mysql_query("SELECT * FROM tbl_gas_meters");
while($row = mysql_fetch_assoc($field)){
echo $row['your field name here'];
}
Please note that, mysql_* functions are deprecated in new php version , so use mysqli or PDO instead.
Thanks! I adapted some of these answers to draw a table from all records from any table, without having to specify the field names. Just paste this into a .php file and change the connection info:
<?php
// Authentication detail for connection
$servername = "localhost";
$username = "xxxxxxxxxx";
$password = "xxxxxxxxxx";
$dbname = "xxxxxxxxxx";
$tablename = "xxxxxxxxxx";
$orderby = "1 DESC LIMIT 500"; // column # to sort & max # of records to display
// Create & check connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); // quit
}
// Run query & verify success
$sql = "SELECT * FROM {$tablename} ORDER BY {$orderby}";
if ($result = $conn->query($sql)) {
$conn->close(); // Close table
$fields_num = $result->field_count;
$count_rows = $result->num_rows;
if ($count_rows == 0) {
die ("No data found in table: [" . $tablename . "]" ); //quit
}
} else {
$conn->close(); // Close table
die ("Error running SQL:<br>" . $sql ); //quit
}
// Start drawing table
echo "<!DOCTYPE html><html><head><title>{$tablename}</title>";
echo "<style> table, th, td { border: 1px solid black; border-collapse: collapse; }</style></head>";
echo "<body><span style='font-size:18px'>Table: <strong>{$tablename}</strong></span><br>";
echo "<span style='font-size:10px'>({$count_rows} records, {$fields_num} fields)</span><br>";
echo "<br><span style='font-size:10px'><table><tr>";
// Print table Field Names
while ($finfo = $result->fetch_field()) {
echo "<td><center><strong>{$finfo->name}</strong></center></td>";
}
echo "</tr>"; // Finished Field Names
/* Loop through records in object array */
while ($row = $result->fetch_row()) {
echo "<tr>"; // start data row
for( $i = 0; $i<$fields_num; $i++ ) {
echo "<td>{$row[$i]}</td>";
}
echo "</tr>"; // end data row
}
echo "</table>"; // End table
$result->close(); // Free result set
?>

Categories