I'm trying to update my database using the html/php table with save button to confirm the changes and save in database.
Here's my Table
How can I edit the 'Quantity' row like text field and save with the button to confirm.
this is my table
<table class=" table-responsive table table-striped table-bordered table-hover ">
<thead>
<tr>
<th>Item #</th>
<th>Description</th>
<th>Unit</th>
<th>Quantity</th>
</tr>
</thead>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "db";
$port = "3306";
$conn = new mysqli($servername, $username, $password, $dbName, $port);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$sql = "SELECT * FROM product";
$result1 = $conn->query($sql);
$result2 = $conn->query($sql);
?>
<tbody>
<?php
while ($row = mysqli_fetch_array($result1)) {
echo "
<tr>
<td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td>" . $row[2] . "</td>
<td>0</td>
</tr>";
}
?>
</tbody>
</table>
Please help. Thanks!
Put your table inside a form.
<form action="give_your_action_page" method="post">
<table class=" table-responsive table table-striped table-bordered table-hover ">
<thead>
<tr>
<th>Item #</th>
<th>Description</th>
<th>Unit</th>
<th>Quantity</th>
</tr>
</thead>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "db";
$port = "3306";
$conn = new mysqli($servername, $username, $password, $dbName, $port);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$sql = "SELECT * FROM product";
$result1 = $conn->query($sql);
$result2 = $conn->query($sql);
?>
<tbody>
<?php
while ($row = mysqli_fetch_array($result1)) {
echo "
<tr>
<td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td>" . $row[2] . "</td>
<td><input type='number name='".$row[1]."' value='".$row[3]."'/></td>
</tr>";
}
?>
</tbody>
</table>
Now at your action page you can access the form values using $_POST array using the value in "Description" field.
For eg : $_POST["banana"] will give the quantity of banana.
Update the database using these values.
You're going to change a field that is not in the database?
because
<tr>
<td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td>" . $row[2] . "</td>
<td>0</td> ----------------> ? (empty) ?
</tr>
You must first create a field called Quantityin your database, then try again if it was a difficult ask questions.
Ok your Code is a really bad , well most of it , and your Q was really hard to understand , but its ok , try to be more accurate next time =) , this answer that i came with is depends on my understanding to what you tried to ask .
I suggest that you topic from w3shool : Select data from database
In my answer or in my Code if we can say that , I used PDO , Whats PDO ?
PDO is an acronym for PHP Data Objects. PDO is a lean, consistent way
to access databases. This means developers can write portable code
much easier. PDO is not an abstraction layer like PearDB. PDO is a
more like a data access layer which uses a unified API (Application
Programming Interface).
Search for it on Google and read some info about how it works and try to learn it , its simple and its the same as ( MYSQLI ) .
This is my Code which i tested it many times and it works , this code can be written in many ways but i tried to make it as simple as i can .
<?php
// Start of the first part ( connect to the database usnig PDO
$servername = "localhost";
$username = "root";
$password = "";
$database = "your database name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// END of the first part
// second part : bring the new quantity from the field
if(isset($_POST['update']))
{
$newquantity = $_POST['newQu'];
$itemName = $_POST['item'];
$UpdateOnQuantity = $conn->prepare( "UPDATE hr SET Quantity = ? WHERE Item = ?");
$UpdateOnQuantity->execute(array($newquantity,$itemName));
if($UpdateOnQuantity)
{
}
else
{
echo "error";
}
}
$FetchNewQuantity = $conn->prepare("SELECT * FROM hr");
$FetchNewQuantity->execute();
?>
<html>
<head>
</head>
<body>
<table class=" table-responsive table table-striped table-bordered table-hover ">
<thead>
<tr>
<th>Item #</th>
<th>Description</th>
<th>Unit</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<?php
while($FetchedData = $FetchNewQuantity->FETCH(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $FetchedData['Item']; ?></td>
<td><?php echo $FetchedData['Description']; ?></td>
<td><?php echo $FetchedData['Unit']; ?><td>
<td><?php echo $FetchedData['Quantity']; ?></td>
<td>
<form action="test2.php" method="POST">
<input type="hidden" name="item" value="<?php echo $FetchedData['Item']; ?>">
<input type="text" name="newQu">
<input type="submit" name="update">
</form>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
This is my code hope it help you , i tested many times as i said so if it did not work with you let me know , and if you did not like PDO just replace PDO code with the normal Mysqli code .
Edit : i edited the code again , did not noticed that you linked your table . i added a while loop so it can show all the data in your table .
Related
I have a select box that shows the names of all the users in the database, however, I need, using a "Find Button" on the selected user on the combo box, that the data attached to that user shows up on the table
Table that currently shows the data of all users
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
$sql = "SELECT * FROM shifts";
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>
And here's the form that shows the users in the select box
<form name="form1" method="POST" action="">
<select name="getUser">
<?php
$res = mysqli_query($db, "SELECT * FROM shifts");
while ($row = mysqli_fetch_array($res))
{
?>
<option><?php echo $row ["name"]; ?></option>
<?php
}
?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
I'm trying to make it that so when the selected user in the combo box and the find button is pressed, that the data found goes all into the table described above.
I was maybe gonna try to attach a variable to the select box and compare it with the names field on the database.
Something like this
$query = "SELECT * FROM shifts WHERE $name == $nameSelected ";
Thanks.
first echo the user id into the option's value
<option value-"<?echo your id?>"><?php echo $row ["name"]; ?></option>
then when your form submits you get get the value from the $_POST
$userId = $_POST['getUser'];
not you can use the variable to query the database, but you should NEVER put it straight in, you should use PDO prepared statements to prevent injection.
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//something like this
$query = $conn->prepare("SELECT * FROM shifts WHERE id = :id");
$query->bindParam(':id',$userId,PDO::PARAM_INT);
$query->execute()
return $query->fetchAll();// I realised you wanted to get all the shifts so you don want fetchAll(),
notice that in mysql we only use a single = for our comparison unlike php. Also i've changed name to the unique row in the database, as unless your name field is unique how do you know which use called Dan you want?
If you want to do this without re-loading the whole page you will need to look into using Ajax and passing the value of the option tag via jQuery.
Here are some places to start:
https://www.w3schools.com/php/php_mysql_connect.asp
https://www.w3schools.com/xml/ajax_intro.asp
if you are not comfortable with javascript (AJAX), try on your form
<?php $res = mysqli_query($db, "SELECT * FROM shifts"); ?>
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"
<select name="getUser">
<option value='All'>All</options>
<?php
while ($row = mysqli_fetch_array($res)) { ?>
<option value='$row ["name"]'><?php echo $row ["name"]; ?></option>
<?php } ?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
And in your table
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
if ($_POST['getUser'] == 'All'){
$sql = "SELECT * FROM shifts";
} else {
$sql = "SELECT * FROM shifts WHERE name = " . $_POST['getUser'];
}
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>
I am using the below syntax within my joomla article and I am in need of a way to add a php button (I know the syntax or this) - and on the button press event fire off exporting the SQL Query Results (header and data) to a csv file. This is the syntax i am using to populate a table. Is this easily ammendable to add in a function to export to .csv also?
<html>
<body>
<form method="POST">
</form>
</body>
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'IP Address';
$option['user'] = 'username';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance($option);
$query = $db->getQuery(true);
$query = "Select height, weight, userID, name from personelinfo;";
$db->setQuery($query);
$query = $db->loadObjectList();
if ($query)
{
?>
<table border="1">
<thead>
<tr>
<th>height </th>
<th>weight </th>
<th>userID </th>
<th>name </th>
</tr>
</thead>
<?php
foreach ($query as $res)
{
print "<tr>";
print "<td>" . $res->height . "</td>";
print "<td>" . $res->weight . "</td>";
print "<td>" . $res->userID . "</td>";
print "<td>" . $res->name . "</td>";
print "</tr>";
}
}
?>
</table>
</html>
You want to have much more separation between your PHP and HTML output. This will serve you well when you want to output other formats such as CSV. Here I get the database results at the top of the file and load them into an array, before any output is done — ideally this would be done in a separate file.
Then we can check if CSV output is desired. I've changed the database code to return an associative array instead of an object, this makes it trivial to pass each row to fputcsv().
Note I've also used alternative syntax and short echo tags to reduce PHP/HTML intermixing. This is a good practice to get into. Finally, your HTML was a mess; you were closing the body before outputting the table, and omitting the <head> and <tbody> elements.
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'IP Address';
$option['user'] = 'username';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance($option);
$query = "Select height, weight, userID, name from personelinfo;";
$db->setQuery($query);
$resultset = $db->loadAssocList();
if (!empty($_GET["csv"])) {
$out = fopen("php://stdout");
header("Content-Type: text/csv");
foreach ($resultset as $res) {
fputcsv($out, $res);
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<?php if(count($resultset):?>
<table border="1">
<thead>
<tr>
<th>height </th>
<th>weight </th>
<th>userID </th>
<th>name </th>
</tr>
</thead>
<tbody>
<?php foreach($resultset as $res):?>
<tr>
<td><?= $res["height"] ?></td>
<td><?= $res["weight"] ?></td>
<td><?= $res["userID"] ?></td>
<td><?= $res["name"] ?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<form method="get">
<button type="submit" name="csv" value="1">Export to CSV</button>
</form>
<?php endif;?>
</body>
</html>
I am running a sql query and getting a count of the results using PHP. The below is the relevant parts of my syntax and what I want to do is if the count returned is >= 1 then display the grid (as it will be populated with 1 or more rows), but if the row count returned is 0 then display a warning on screen notifying the user.
My issue with the code is that it always returns the grid!
<?php
//Connection to server to run sql query and return results
$numofrows = mssql_num_rows($tsql);
?>
if ($numofrows >= 1) {
//Build out HTML Table
} else {
//write on screen there are no results to display
}
EDIT
This is how I am setting it up which appears to be the same as the link in the comments
<?php
//Connection to server to run sql query and return results
$numofrows = mssql_num_rows($tsql);
?>
if ($numofrows >= 1) {
<table border="1">
<thead>
<tr>
<th >Header 1 </th>
<th>Header 2 </th>
<th>Header 3 </th>
<th>Header 4 </th>
<th>Header 5</th>
<th>Header 6 </th>
</tr>
</thead>
<tbody>
<?php
foreach( $query as $res ) {
print "<tr>";
print "<td>" .$res->Field1."</td>";
print "<td>" .$res->Field2."</td>";
print "<td>" .$res->Field3."</td>";
print "<td>" .$res->Field4."</td>";
print "<td>" .$res->Field5."</td>";
print "<td>" .$res->Field6."</td>";
print "</tr>";
}
?>
} else {
echo "<strong>No Results</strong>"
}
Here's an approximate example, to help you out.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Select Database
mysqli_select_db($conn, "test");
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body bgcolor="#06160F">
<table frame="hsides" style="color:#ffffff;">
<!-- Headers of the table -->
<tr>
<th>Header 1 </th>
<th>Header 2 </th>
<th>Header 3 </th>
<th>Header 4 </th>
<th>Header 5</th>
<th>Header 6 </th>
</tr>
</table>
</div>
<div>
<div>
<table border="1" width="960px">
<?php
$sql = "SELECT * FROM abc";
$result = mysqli_query($conn,$sql);
if($result)
{
if ($result->num_rows > 0)
{echo"<table>";
// output data of each row
while($row = $result->fetch_assoc())
{
echo"<tr>";
echo"<td width=120px align=\"center\">".$row["feild1"]."</td>";
echo"<td width=170px align=\"center\">".$row["feild2"]."</td>";
echo"<td width=120px align=\"center\">".$row[""feild3"]."</td>";
echo"<td width=170px align=\"center\">".$row["feild4"]."</td>";
echo"<td width=420px align=\"center\">".$row["feild5"]."</td>";
echo"<td width=420px align=\"center\">".$row["feild6"]."</td>";
echo"</tr>";
}
echo"</table>";
}
else
echo "<h3 align=\"center\">Nothing to show.</h3>";
}
else
echo "<br> Database error.";
$conn->close();
?>
</table>
</div>
<br>
</div>
</body>
</html>
By the way I'm using MySQL.
You can also check this answer: Checking for empty result (php, pdo, mysql)
I think also, you should use PDO.
Your if loop is outside the php section, so it won't be evaluated
So far, I have this program that links my phpmyadmin database to my php script. Now, I need to display certain things in a table like "all records," "all contacts whose last name starts with S," "all pet owners," etc. My question is: is there a simpler way to insert code into my php script to display the information from my database. Right now I have that long echo statement to display the information. Is there a way I can just use something like a SELECT * statement to display all records and to simplify my code?
<?php
$db_hostname='localhost';
$db_username='root';
$db_password='';
$db_database='Address Book';
$connection = new mysqli( $db_hostname,
$db_username,
$db_password,
$db_database);
if ($connection->connect_error) {
echo "Sorry";
} else {
echo "Connected!<br><br>";
$sql = "SELECT * FROM People";
$result = $connection->query($sql);
if (!$result) die ($connection->error);
$n = $result->num_rows;
for ($i=1; $i<=$n; $i++) {
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<table>
<tr><th>ID</th><th>First Name</th><th>Last Name</th>
<th>Street Address</th><th>City</th>
<th>State</th><th>Zip Code</th>
<th>Email Address</th><th>Comment</th>
<th>Number of pets</th></tr>";
echo "<tr><td width=20>" . $row['iD'] . "</td><td>" . $row['First Name'] . "</td><td width=40>" .
$row['Last Name'] . "</td><td width=200>" . $row['Street Address'] . "</td><td width=30>" .
$row['City'] . "</td><td width=40>" . $row['State'] . "</td><td width=30>" .
$row['Zip Code'] . "</td><td width=40>" . $row['Email Address'] . "</td><td width=20>" .
$row['Comment'] . "</td><td width=10>" . $row['Number of pets'] . "</td></tr>";
}
echo "</table>";
}
?>
You should a table structure first then insert your PHP codes within the structure. E.g:
<?php
// Put your MYSQLI retrievals codes here
?>
<table>
<tr>
<th>FIELD_1</th>
<th>FIELD_2</th>
<th>FIELD_3</th>
</tr>
<?php
while ($rows = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<tr>
<td><?php echo $rows['field_1']; ?></td>
<td><?php echo $rows['field_2']; ?></td>
<td><?php echo $rows['field_3']; ?></td>
</tr>
<?php
}
?>
</table>
Technically you are doing everything alright, but there are some more sophisticated ways to develop the things you want.
Take a look at the following links:Object oriented programming in PHP and templating in PHP.
Hope this works for you:
<?php
$db_hostname='localhost';
$db_username='root';
$db_password='';
$db_database='Address Book';
$connection = new mysqli($db_hostname,$db_username,$db_password,$db_database);
if ($connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
echo "Connected!<br><br>";
}
$last_name = "Lastname to search"; //You can post or get lastname in here.
/* create a prepared statement */
if ($sql = $connection->prepare("SELECT * FROM People WHERE `Last Name`=?")) {
/* bind parameters for markers */
$sql->bind_param("s", $last_name);
/* execute query */
$sql->execute();
/* instead of bind_result: */
$result = $sql->get_result();
/* close statement */
$sql->close();
}
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Street Address</th>
<th>City</th>
<th>State</th>
<th>Zip Code</th>
<th>Email Address</th>
<th>Comment</th>
<th>Number of pets</th>
</tr>
</thead>
<tbody>
<?
/* now you can fetch the results into an array */
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td width=20><?=$row['iD'];?></td>
<td><?=$row['First Name'];?></td>
<td width=40><?=$row['First Name'];?></td>
<td width=200><?=$row['Street Address'];?></td>
<td width=30><?=$row['City'];?></td>
<td width=40><?=$row['State'];?></td>
<td width=30><?=$row['Zip Code'];?></td>
<td width=40><?=$row['Email Address'];?></td>
<td width=20><?=$row['Comment'];?></td>
<td width=10><?=$row['Number of pets'];?></td>
</tr>
<?
}
?>
</tbody>
</table>
I am trying to make something so it shows the database results. The problem is, it only shows 1 result. I want it to show multiple results using an quick and dirty template system. Also, is there a way to make my system better? Perhaps a class or a function? I need some insight on this. Thanks a bunch!
cp.php
<?php
require("db.php");
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
$title = "********";
require("templates/header.php");
if($mybb->user['uid'])
{
$uid = $mybb->user['uid'];
// Active Tournaments
// run queries, do all the brainwork
// lets get the forum name
$query = "SELECT tourneys.name, tourneys.date, tourneys.time
FROM tourneys
INNER JOIN players ON players.tid = tourneys.id
WHERE players.forumname = {$uid}";
$result = mysqli_query($conn, $query);
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$activetournaments = "<td>". $row['name'] ."</td><td>" . $row['date'] . "</td><td>". $row['time'] ."</td>";
// $team = mysqli_query($conn, "SELECT * FROM tourneys WHERE id=" . $row['tid'] . "");
// $playing = mysqli_query($conn, "SELECT `` FROM tourneys WHERE id=" . $row['tid'] . "");
}
}
else
{
$error = "Only registered members may access this area.";
include ('templates/error.php');
}
require ("templates/cp.php")
?>
templates/cp.php
<h2>Welcome back <?=$mybb->user['username']; ?>!</h2>
<?=$postrequirement?>
<h3>Active Tournaments</h3>
<table>
<tr>
<th>Name</th>
<th>Date/time</th>
<th>Team</th>
<th>Playing as</th>
<th>Options</th>
</tr>
<tr>
<?=$activetournaments?>
</table>
<hr />
<h3>Participated Tournaments</h3>
<table>
<tr>
<th>Position</th>
<th>Name</th>
<th>Date/time</th>
<th>Team</th>
<th>Played as</th>
<th>Options</th>
</tr>
<tr>
<?=$participatedtournaments?>
</table>
I have changed $activetournaments to append to the end using '.='.
while($row = mysqli_fetch_assoc($result)) {
$activetournaments .= "<td>". $row['name'] ."</td><td>" . $row['date'] . "</td><td>". $row['time'] ."</td> ";
}
At the moment, for each record, it is overwriting $activetournaments. You could also use $activetournaments as an array then do a while / foreach in the template.
In your cp.php you overwrite $activetournaments in each while execution, change your code to:
<?php
require("db.php");
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
$title = "1ShotGG Tournaments | Control Panel";
require("templates/header.php");
if($mybb->user['uid'])
{
$uid = $mybb->user['uid'];
// Active Tournaments
// run queries, do all the brainwork
// lets get the forum name
$query = "SELECT tourneys.name, tourneys.date, tourneys.time
FROM tourneys
INNER JOIN players ON players.tid = tourneys.id
WHERE players.forumname = {$uid}";
$result = mysqli_query($conn, $query);
// output data of each row
$activetournaments = '';
while($row = mysqli_fetch_assoc($result)) {
$activetournaments .= "<td>". $row['name'] ."</td><td>" . $row['date'] . "</td><td>". $row['time'] ."</td>";
// $team = mysqli_query($conn, "SELECT * FROM tourneys WHERE id=" . $row['tid'] . "");
// $playing = mysqli_query($conn, "SELECT `` FROM tourneys WHERE id=" . $row['tid'] . "");
}
}
else
{
$error = "Only registered members may access this area.";
include ('templates/error.php');
}
require ("templates/cp.php")
?>
In your templates/cp.php you can add a </tr> tag here:
<tr>
<?=$activetournaments?>
</tr>
your new templates/cp.php:
<h2>Welcome back <?=$mybb->user['username']; ?>!</h2>
<?=$postrequirement?>
<h3>Active Tournaments</h3>
<table>
<tr>
<th>Name</th>
<th>Date/time</th>
<th>Team</th>
<th>Playing as</th>
<th>Options</th>
</tr>
<tr>
<?=$activetournaments?>
</tr>
</table>
<hr />
<h3>Participated Tournaments</h3>
<table>
<tr>
<th>Position</th>
<th>Name</th>
<th>Date/time</th>
<th>Team</th>
<th>Played as</th>
<th>Options</th>
</tr>
<tr>
<?=$participatedtournaments?>
</table>