I have table which is populated from mysql. One of the rows is status which is 0 by default and is have dropdown menu where I can choose 1 or 2. Then there is button update which should update that row in the table. The problem is that didn't update.
this is the table form
if(isset($_GET['rest_id']) && is_numeric($_GET['rest_id'])){
$rest_id = $_GET['rest_id'];
$query = mysqli_query($con, "SELECT * FROM reservation
WHERE table_res_id = $rest_id
ORDER BY `DateTime` DESC ");
echo "</p>";
// display data in table
echo '<table class="table table-striped table-bordered responsive">';
echo "<thead>";
echo '<tr>
<th>Name</th>
<th>Comment</th>
<th>Status</th>
<th></th>
</tr>
</thead>';
echo '<div class="row">';
echo '<div class="box col-md-12">';
echo '<div class="box-content">';
echo "<tbody>";
// loop through results of database query, displaying them in the table
while ($res = mysqli_fetch_assoc($query))
{
echo '<tr>';
echo '<td>' . $query['name'] . '</td>';
echo '<td>' . $query['comment'] . '</td>';
echo '<td>
<div class="btn-group">
<select>
<ul class="dropdown-menu">
<li><option> Status:'. $query['status'] .'
<span class="caret"></span>
</option></li>
<li><option>1</option></li>
<li><option>2</option></li>
</ul>
</select>
</div>
</td>';
echo '<td>
<a class="btn btn-info" href="users/Confirm.php?id=' . $query['id'] . '">
<i class="glyphicon glyphicon-edit icon-white"></i>
Change status</a></td>';
echo "</tr>";
This is confirm.php
session_start();
include '../misc/db.inc.php';
ob_start();
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
$query = "SELECT * FROM reservation WHERE id=$id" or die(mysqli_error($con));
$res = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($res);
if ($stmt = $con->prepare("UPDATE reservation SET status = ? LIMIT 1"))
{
$stmt->bind_param("i",$res['status');
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$con->close();
As per your code your are sending database value again to confirm.php not the user selected value.
For this, assign name to like ..and instead of anchor click use form submission.. it will work.
Another solution.
You can call onchange event on where javascript function will get call and will update selected value in database via Ajax..Hope this logic will help you
According to our previous comments:
Make a button <input type="button" onclick="saveChange('.$id.')"/>
Then set the function 'url' to users/confirm.php
and set the 'data' to the id..
function saveChange(id){
$.ajax({
type: "POST",
url: "users/confirm.php",
data: 'id='+id
});
}
Old
I suggest you use something like that:
$.ajax({
type: "POST",
url: "save.php",
data: data,
success: function(msg){}
});
with onchange="" event, and at save.php you simply use an update method.
By the way
$query = "SELECT * FROM reservation WHERE id=$id" or die(mysqli_error($con));
$res = mysqli_query($con, $query);
was ment to be like:
$query = "SELECT * FROM reservation WHERE id=$id";
$res = mysqli_query($con, $query) or die(mysqli_error($con));
Related
I am new to PHP and here I have a problem navigating to another page by clicking in one of the rows of the table. I want also to pass the values of that row to the next page and display them there.
Here is my code:
<body>
<div class="wrapper">
<h1>List of customers</h1>
<?php
require_once "db_settings.php";
$sql = "SELECT id, username FROM customers";
$result = $dbi->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Username</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr> <td>".$row["id"]."</td> <td>".$row["username"]." </td> </tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</body>
</html>
You have to add "a" tag with GET link:
while($row = $result->fetch_assoc()) {
echo "<tr> <td>".$row["id"]."</td> <td><a href='new_url?user_id=".$row["id"]."'>".$row["username"]." </a></td> </tr>";
}
and in the new_url page use
$user_id = $_GET['user_id']
and now you can use the id to get the user from the database again
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 created a database where I store some pieces of data and display them on the HTML table, I put a delete button but when I run the script to delete it rather refreshes it
I don't know where it fails, and down here is my code of the table
<table class="table table-striped table-advance table-hover">
<tbody>
<?php
$conn = mysqli_connect("localhost", "blog", "0000", "blog");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($conn,"SELECT * FROM room_details ");
echo "<tr>
<th> Room Name</th>
<th> Room No.</th>
<th> Type</th>
<th> Price</th>
<th> Action</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['room_name']."</td>";
echo "<td>".$row['room_number']."</td>";
echo "<td>".$row['room_type']."</td>";
echo "<td>".$row['room_price']."</td>";
echo "<td>"?><div class="btn-group">
<a class="btn btn-danger" name="delete"
href="incl/process.php?delete=<?php echo $row['id']; ?>">DELETE<i
class="icon_close_alt2"></i></a>
</div></td>
<?php echo "</tr>";
} ?>
</tbody>
</table>
and this is delete processing code,
<?php
$conn = mysqli_connect("localhost", "blog", "0000", "blog");
if(isset($_GET['delete'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("DELETE FROM room_details WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
header("Refresh: 2; url=rooms.php");
echo '<div class="alert alert-info fade in">
<strong>SUCCESS!!</strong> Data deleted!.
</div>';
}
?>
It doesn't delete the row but now it hangs on process.php nothing is happening, where did I go wrong?
Apart from that you have to set the $id using $id = $_GET['delete']; instead of $id = $_GET['id']; because delete is what you are passing in the query string, the prepare method should be called on $conn.
Change this line:
$stmt = $mysqli->prepare("DELETE FROM room_details WHERE id = ?");
To this line:
$stmt = $conn->prepare("DELETE FROM room_details WHERE id = ?");
Not entirely sure why it's hanging, but you haven't set a variable called 'id'. Should be:
$id = $_GET['delete'];
i used the crud delete method and it works for me, but when i tried it with a different database and table it keeps saying "Invalid argument supplied for foreach()"
this is my "vacature-verwijderen.php" where you should be able to delete it
<div>
<table id="tabel">
<thead>
<tr>
<th>Functie</th>
<th>Omschrijving</th>
<th>Salaris</th>
</tr>
</thead>
<tbody>
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM vacature ORDER BY id DESC';
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['functie'] . '</td>';
echo '<td>'. $row['omschrijving'] . '</td>';
echo '<td>'. $row['salaris'] . '</td>';
echo '<td width=250>';
echo '<a class="button " href="update.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="button" href="delete.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div>
and then when you click delete you go to "delete.php" which looks like this
<?php
require 'database.php';
$id = 0;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( !empty($_POST)) {
$id = $_POST['id'];
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM vacature WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
Database::disconnect();
header("Location: vacature-verwijderen.php");
}
?>
i don't know what is wrong since it used to work, also my database table looks like this
foreach ($pdo->query($sql) as $row) {
That's what is wrong. $pdo->query($sql) already returns your $row.
Use a while instead so that it do the query and returns you the new row as long as there is data to fetch :
while ($row = $pdo->query($sql)) {
Also :
$sql = "DELETE FROM vacature WHERE id = ?";
The table you provided doesn't contain any field named id, although there is one named vacature_id. You might want to change that too :
$sql = "DELETE FROM vacature WHERE vacature_id = ?";
Don't hesitate to come back if it doesn't solve your issue.
I have this server side table that works fine, except it has modals, but I need to open another PHP edit page(not as modal), linked to the row-id selected.
</div>
<div class="table-responsive">
<table id="users_data" class="table table-bordered table-striped">
<thead>
<tr>
<th data-column-id="id" data-type="numeric">No</th>
<th data-column-id="idno">Id No</th>
<th data-column-id="surname">Surname</th>
<th data-column-id="firstname">Firstname</th>
<th data-column-id="category_name">Category</th>
<th data-column-id="age">Age</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#users_form')[0].reset();
$('.modal-title').text("Add New Users");
$('#action').val("Add");
$('#operation').val("Add");
});
var usersTable = $('#users_data').bootgrid({
ajax: true,
rowSelect: true,
post: function()
{
return{
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "fetch.php",
formatters: {
"commands": function(column, row)
{
return "<button type='button' class='btn btn-warning btn-xs update' data-row-id='"+row.id+"'>Edit</button>" +
" <button type='button' class='btn btn-danger btn-xs delete' data-row-id='"+row.id+"'>Delete</button>";
}
}
});
Where the buttons are, I need something like this:
<td><span class="glyphicon glyphicon-pencil" aria-hidden="true" </span><b><font size="3" color="red"</font> Edit<b></td>
Currently it uses this modal info:
$(document).on("loaded.rs.jquery.bootgrid", function()
{
usersTable.find(".update").on("click", function(event)
{
var id = $(this).data("row-id");
$.ajax({
//url:"update2.php",
url:"fetch_single_entries.php",
method:"POST",
data:{id:id},
dataType:"json",
success:function(data)
{
$('#usersModal').modal('show');
$('#categories').val(data.categories);
$('#idno').val(data.idno);
$('#surname').val(data.surname);
$('#firstname').val(data.firstname);
$('#age').val(data.age);
$('.modal-title').text("Edit User");
$('#id').val(id);
$('#action').val("Edit");
$('#operation').val("Edit");
}
});
});
});
The fetch.php for the table data looks like this:
<?php
//fetch.php
include("connection.php");
$query = '';
$data = array();
$records_per_page = 10;
$start_from = 0;
$current_page_number = 0;
if(isset($_POST["rowCount"]))
{
$records_per_page = $_POST["rowCount"];
}
else
{
$records_per_page = 10;
}
if(isset($_POST["current"]))
{
$current_page_number = $_POST["current"];
}
else
{
$current_page_number = 1;
}
$start_from = ($current_page_number - 1) * $records_per_page;
$query .= "
SELECT
users.id,
tblcategories.category_name,
users.idno,users.surname,users.firstname,
users.age FROM users
INNER JOIN tblcategories
ON tblcategories.category_id = users.category_id ";
if(!empty($_POST["searchPhrase"]))
{
$query .= 'WHERE (users.id LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR tblcategories.category_name LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.idno LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.surname LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.firstname LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.age LIKE "%'.$_POST["searchPhrase"].'%" ) ';
}
$order_by = '';
if(isset($_POST["sort"]) && is_array($_POST["sort"]))
{
foreach($_POST["sort"] as $key => $value)
{
$order_by .= " $key $value, ";
}
}
else
{
$query .= 'ORDER BY users.id DESC ';
}
if($order_by != '')
{
$query .= ' ORDER BY ' . substr($order_by, 0, -2);
}
if($records_per_page != -1)
{
$query .= " LIMIT " . $start_from . ", " . $records_per_page;
}
//echo $query;
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
$query1 = "SELECT * FROM users";
$result1 = mysqli_query($connection, $query1);
$total_records = mysqli_num_rows($result1);
$output = array(
'current' => intval($_POST["current"]),
'rowCount' => 10,
'total' => intval($total_records),
'rows' => $data
);
echo json_encode($output);
?>
Please assist this novice programmer about how to adjust the code.
Sounds like you just want to convert an jquery ajax edit thing on a modal dialogue into an actual HTML edit page. Replace all of that jquery with just a link to a new page you create, and on that page just have a form with the stuff in it. The first thing you'll want is to check if it's a GET or a POST request - if GET, query from the database for the values and display the standard HTML form. If it's a POST, update the database with the new values (after optionally doing some processing).
Hopefully that's the question you're asking? If so, sorry the answer is so broad, but the question is kind of broad too. Feel free to clarify further if there's a specific problem you're encountering trying to get the above to work.
Here is how to add the links:
return "<button type=\"button\" class=\"btn btn-xs btn-warning\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-pencil\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-danger\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";