how to display an sqli database - php

I need to be able to display the contents of my database but I am not sure how to do this using sqli, any help provided will be appreciated
<?php
ini_set("display_errors",1);
error_reporting(E_ALL);
$servername = "server";
$username = "username";
$password = "password";
$dbname = "sql1702520";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
I tried to use a mysql query bellow to extract the data from the database, however i have been told that it is not possible to use mysql and sqli
/*
$result = mysql_query("SELECT * FROM sql1702520 ");
*/
$conn->close();
?>
Html to display the database
<html>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>image</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
Tried using this to display the table data however mysql would be required to do it this way
while( $row1 = mysqli_fetch_assoc( $result ) ){
foreach ($row1 as $row){
?>
<tr>
<td><?php $row['id'] ?></td>
<td><?php $row['hname'] ?></td>
<td><?php $row['himage'] ?></td>
<td><?php $row['hdesc'] ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<?php mysql_close($connector); ?>
</body>
</html>

assuming that your tablename (what looks suspiciously like your database name) for mysqli you would have to use the mysqli_query function to send your query.
$result = mysql_query($conn,"SELECT * FROM sql1702520 ");
and mysqli_fetch_assocfor your loop
$row = mysqli_fetch_assoc($result);
you can ditch the for-each loop. the while loop is sufficient.
for further help an error message would help.

Related

Need to be able to search by a field in a table from form input

I need to add a form input to search for a second column in a table.
I have tried adding a form. Tried manually putting what I am looking for in the SELECT line and it finds the data. Just need to be able to find it with form input.
<?php
/**
* Mark as Paid
*/
require "../config.php";
require "../common.php";
$success = null;
if (isset($_POST["submit"])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_POST["submit"];
$sql = "UPDATE consignsold SET paid='y' WHERE paid='n' AND sold='y' AND itemnumber = $itemnumber";
$statement = $connection->prepare($sql);
$statement->bindValue(':itemnumber', $itemnumber);
$statement->bindValue(':paid', $paid);
$statement->bindValue(':sold', $sold);
$statement->execute();
$success = "Item successfully updated";
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT * FROM consignsold WHERE paid='n'";
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
?>
<?php require "templates/header.php"; ?>
<h2>Mark Items as Paid</h2>
<?php if ($success) echo $success; ?>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<form method="post">
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<table>
<thead>
<tr>
<th>Sale Number</th>
<th>Item Number</th>
<th>Lot Number</th>
<th>Category</th>
<th>Item Description</th>
<th>Reserve</th>
<th>Seller Number</th>
<th>Amount</th>
<th>Buyer Number</th>
<th>Sold</th>
<th>Paid</th>
<th>Mark</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) : ?>
<tr>
<td><?php echo escape($row["salenumber"]); ?></td>
<td><?php echo escape($row["itemnumber"]); ?></td>
<td><?php echo escape($row["lotnumber"]); ?></td>
<td><?php echo escape($row["category"]); ?></td>
<td><?php echo escape($row["itemdescription"]); ?></td>
<td><?php echo escape($row["reserve"]); ?></td>
<td><?php echo escape($row["sellernumber"]); ?></td>
<td><?php echo escape($row["amount"]); ?></td>
<td><?php echo escape($row["buyernumber"]); ?></td>
<td><?php echo escape($row["sold"]); ?></td>
<td><?php echo escape($row["paid"]); ?></td>
<td><button type="submit" name="submit" value="<?php echo escape($row["itemnumber"]); ?>">Mark as Paid</button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</form>
<br>
<?php require "templates/footer.php"; ?>
If I try to add a form, I get a blank page. I expect a form with a place to input Buyer Number. As-is, the page works but displays all items and the operator has to manually find each item by buyer number and click the Mark as Paid button. What I need it to do is have an input where it asks for buyer number and only list those items with the mark button at the end. It is a closed-circuit operation so not worried about injections at this time.
The line: $sql = "SELECT * FROM consignsold WHERE paid='n'";
would be changed to something like: $sql = "SELECT * FROM consignsold WHERE paid='n' AND buyernumber = <from form input>";
Some have asked to clarify. . . I thought it was pretty clear to start with but. . .
REVISION: What I need on that page is a form input that asks the operator for a buyernumber and then uses the input from that form in the SELECT line to look for buyernumber and sold = 'y'. "buyernumber" is a column and "sold" is a column in the table: consignsold.
Thanks again to all who try to help!
I am not entirely sure, I understand your question, but let me answer what I see is wrong.
First of all you should not catch the exceptions. This is considered a bad practice.
You also do not need 3 binds, you can just pass $itemnumber in the execute(). For this however you need to put a placeholder in the query. ? is simpler than a named placeholder.
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_POST["submit"];
$sql = "UPDATE consignsold SET paid='y' WHERE paid='n' AND sold='y' AND itemnumber=?";
$statement = $connection->prepare($sql);
$statement->execute([$itemnumber]);
$success = "Item successfully updated";

How to make a member list with database?

How do I make a member list with PHP and MySQL?
I have user accounts, login and that stuff. How do I make a page that shows all the members?
I can provide code!
NOTE: Your question is not clear. You have not included any code or query snippet. I will try my best to answer your question.
As per my knowledge I think your users are nothing but the members. Just write a query to pull all the users from the users table and display.
NOTE : I will use mysqli_* function without any escaping please help yourself.
<?php
include_once 'db_connect.php'; /Line to include the database connection file, which had $link as resource */
$membersQuery = mysqli_query($link, "SELECT * FROM users");
$members = array();
if(mysqli_num_rows($membersQuery) > 0){
while($row = mysqli_fetch_assoc($membersQuery)){
$members[] = $row; //Get all the members row by row and store in $members array
}
}
?>
<table>
<thead>
<tr>
<th>Firstname</th>
</tr>
</thead>
<tbody>
<?
if(count($members) > 0){
foreach($members as $member){
<tr>
<td><?php echo $member['firstname']; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
Even while looping in table you can use the following command
<tbody>
<?
if(mysqli_num_rows($membersQuery) > 0){
while($member = mysqli_fetch_assoc($membersQuery)){
<tr>
<td><?php echo $member['firstname']; ?></td>
</tr>
<?php
}
}
?>
</tbody>

MySQL PHP While loop

I'm in need of some help. I'm working in dreamweaver and I'm trying to insert values from my MySQL database into a table on my HTML page.
Dreamweaver generated these variables for me from the server behaviours
mysql_select_db($database_connection, $connection);
$query_mwAcc = "SELECT * FROM accounts";
$mwAcc = mysql_query($query_mwAcc, $connection) or die(mysql_error());
$row_mwAcc = mysql_fetch_assoc($mwAcc);
$totalRows_mwAcc = mysql_num_rows($mwAcc);
Now what I need help with is what to put into the while loop for my PHP script, this is what I have so far
<table class="table table-bordered">
<?php while (): ?>
<tr>
<td><?php echo $row['id'] ?></td>
</tr>
<?php endwhile; ?>
</table>
You need to write your fetch command within the while loop itself.
$query_mwAcc = "SELECT * FROM accounts";
$mwAcc = mysql_query($query_mwAcc, $connection) or die(mysql_error());
while($row_mwAcc = mysql_fetch_assoc($mwAcc)) {
?>
<tr>
<td><?php echo $row_mwAcc['id'] ?></td>
</tr>
<?php } ?>
</table>
With an update to use PDO you can change the while loop into a foreach on the query result. PDO should be used over mysql_ interface methods, due to deprecation: Why shouldn't I use mysql_* functions in PHP?
<?php
$dbh = new PDO('mysql:host=...;dbname=...', $user, $pass);
$results = $dbh->query('SELECT * FROM accounts');
?>
<table class="table table-bordered">
<?php foreach ($results as $row): ?>
<tr>
<td><?php echo $row['id'] ?></td>
</tr>
<?php endforeach; ?>
</table>

Can't list result from sql to html table

Trying to list the data from mysql to a html table using php in main html file. I've been through all of the other questions on here and I'm sure I have mostly the same methods and code as them.
For some reason (which I suspect has something to do with mysql and not the code) the only result is a blank table with one row and five columns. Each time I try to implement the other codes they just seem to print text onto the site.
I'm very confused as I think I've done the right thing. I've even been able to list the data from mysql through php echo so I know it's there and that I can access it. Really would appreciate some help on this. Thank you.
<table border="1">
<tbody>
<?php
$connect = mysqli_connect("localhost", "daemon", "xampp", "test");
if (!$connect) {
die(mysqli_error());
}
$results = mysqli_query("SELECT title,url,details,file,submission_date FROM input");
while($row = mysqli_fetch_array($results)) {
?>
<td><?php echo $row['title']?></td>
<td><?php echo $row['url']?></td>
<td><?php echo $row['details']?></td>
<td><?php echo $row['file']?></td>
<td><?php echo $row['submission_date']?></td>
<?php
}
?>
</tbody>
</table>
You say this code is in your mail html file? And it is printing out onto the screen? Try changing your file to .php not .html! Php code won't run in a .html file, and will likely output your code directly onto the page.
Mysqli_query expect connection link as first parameter.
$results = mysqli_query($connect, "SELECT title,url,details,file,submission_date FROM input");
Just a quick not so related improvement. You can avoid inserting most of the php opening and closing clauses:
...
while($row = mysqli_fetch_array($results)){
echo "<td>".$row['title']."/td>";
echo "<td>".$row['url']"</td>";
...
}
?>
Use <tr> because table must have atleast one row(<tr>) and one column(<td>)
<table border="1">
<tbody>
<tr>
<?php
$connect = mysqli_connect("localhost", "daemon", "xampp", "test");
if (!$connect) {
die(mysqli_error());
}
$results = mysqli_query("SELECT title,url,details,file,submission_date FROM input");
while($row = mysqli_fetch_array($results)) {
?>
<td><?php echo $row['title']?></td>
<td><?php echo $row['url']?></td>
<td><?php echo $row['details']?></td>
<td><?php echo $row['file']?></td>
<td><?php echo $row['submission_date']?></td>
<?php
}
?>
</tr>
</tbody>
<table border="1">
<tbody>
<?php
$connect = mysqli_connect("localhost", "daemon", "xampp", "test");
if (!$connect) {
die(mysqli_error());
}
$results = mysqli_query($connect, "SELECT title,url,details,file,submission_date FROM input");
if (!$results) {
mysqli_error($results);
die();
}
while ($row = mysqli_fetch_array($results)) {
?>
<tr>
<td><?php echo $row['title'] ?></td>
<td><?php echo $row['url'] ?></td>
<td><?php echo $row['details'] ?></td>
<td><?php echo $row['file'] ?></td>
<td><?php echo $row['submission_date'] ?></td>
</tr>
<?php
}
?>
</tbody>
</table>

HTML table with sql data in php (table row depend by sql columns)

Hello i got this sample data in sql
$data = array(
array('id' => '1','name' => 'name1','surname' => 'surname1'),
array('id' => '2','name' => 'name2','surname' => 'surname2'),
array('id' => '3','name' => 'name3','surname' => 'surname3'),
array('id' => '4','name' => 'name4','surname' => 'surname4')
);
I want to dispplay in in html table but my code didnt work :
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
}
?>
<tbody>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
</tbody>
</table>
</body>
</html>
But i wann't also that the numer of rows in html table depends by number of columns in sql table. For example in this case i want to display only three rows (three columns in sql table). When i add the column's to sql table i want to rows in html output table increses dynamicly.
Could someone help me with this code ?
Change your code to this:
<tbody>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php
}
?>
</tbody>
You are closing your while loop before displaying the results
You close your while-loop not correct:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
$result = mysql_query($select_data);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<tbody>
<?php while ($data = mysql_fetch_row($result)):?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php endwhile;?>
</tbody>
</table>
</body>
</html>
Using the the "while(cond):" and "endwhile;" command you can see better where something starts and where it ends than using the encapsulation with braces.
Please consider to switch your Database Wrapper from mysql_ to PDO or mysqli, since mysql is not anymore actively supported.
You could also use instead:
<?php echo $data['id']?>
rather the shortform:
<?=$data['id']?>
Which is also avaiable w/o php short open after 5.3 (I think it was 5.3)
If I understand your question correctly, you would like to have the number of returned rows match the number of columns in your table dane. The following code should do just that and I'm using mysqli which I strongly recommend. The mysql_query extension is deprecated as of PHP 5.5.0.
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to the database ' . $db->connect_error);
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$result = $db->query($select_cols)){
die('There was an error running the query.');
}
while($row = $result->fetch_assoc()){
$cols[] = $row['column_name']; // Store the columns to an array. It will be further used.
}
// Implode the column names to a comma delimited string to use in the next select. It's also a good practice not to use asterisk in your select statements
$table_headers = implode(',', $cols);
// Query for records with a limit to number columns in the $table_name
$select_data = "SELECT $table_headers FROM $table_name ORDER BY `id` DESC LIMIT 0 , $result->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query ' . $db->error);
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into an array to be used in the html table
}
$db->close(); // Close our connection
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<?php foreach ($cols as $k) : // Loop through columns ?>
<th align="center" valign="middle"><?php echo $k; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ($data as $k) : // Loop through each $data array() ?>
<tr>
<?php foreach ($k as $v) : // Let's display the records ?>
<td align="center" valign="middle"><?php echo $v; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
I also took the liberty to dynamically display the column names as table headers which should eliminate the need to manually add them later when your columns increase. If you would like to manually create them simply replace the top php portion with this one:
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$num_cols = $db->query($select_cols)){
die('There was an error running the query.');
}
$select_data = "SELECT * FROM $table_name ORDER BY `id` DESC LIMIT 0 , $num_cols->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into array to be used in the html table
}
$db->close(); // Close our connection
// print_r('<pre>');
// print_r($data);
// print_r('</pre>');
?>
and adjust the html code between <thead></thead>. This entire sample was put together pretty quickly so it could definitely be improved and adjusted to whatever needs. Please inspect it for any typos as well.

Categories