PHP PDO Table and seperate buttons - php

noob here. I am trying to create a table where I can put in separate buttons that link to my next .php page and to certain information from the next page tables. I have tried for hours and hours to get a style of table pdo that will allow me to add my own separate buttons with link to my next .php page.
But without adding one input href that creates a button for all of the rows.
Unless there is a way to add it to the single href section. But I have no idea. The links work but just point to the next page as a whole instead of choosing a table.
There are 3 tables on the next .php page, taken from mysql databases. Here is my index.php page. It is just basic for now until I can get the php code to work. I take it there is something to do with superglobals or sessions?? Thanks in advance.
<html>
<head>
<title>Blah</title>
<H1>Blah</H1>
<H2>Blah</H2>
<body>
<?php
include 'mystyles.css';
?>
<?php
$user = '123';
$pass = '456';
$db = new PDO( 'mysql:Myhost;dbname=123', $user, $pass );
$sql = "SELECT * FROM Production";
$query = $db->prepare( $sql );
$query->execute();
$results = $query->fetchAll( PDO::FETCH_ASSOC );
?>
<table class="table">
<tr>
<th>Title</th>
<th>Ticket Cost</th>
<th></th>
<?php
foreach( $results as $row ){
echo "<tr><td>";
echo $row['Title'];
echo "</td><td>";
echo $row['BasicTicketPrice'];
echo ('<td><a href="perf.php"><input type="submit" name="submit"
value="Register" class="register" /></a></td>');
echo "</tr>";
}
?>
</table>
</body>
</html>

One way is You need to pass the value to next page via GET ie in the URL
For eg:
....
This will result like ......
Once user clicks the link value will be passed to next page via GET, u can u use that value for computation
Sample
<html>
<head>
<title>Blah</title>
<H1>Blah</H1>
<H2>Blah</H2>
<body>
<?php
include 'mystyles.css';
?>
<?php
$user = '123';
$pass = '456';
$db = new PDO( 'mysql:Myhost;dbname=123', $user, $pass );
$sql = "SELECT * FROM Production";
$query = $db->prepare( $sql );
$query->execute();
$results = $query->fetchAll( PDO::FETCH_ASSOC );
?>
<table class="table">
<tr>
<th>Title</th>
<th>Ticket Cost</th>
<th></th>
<?php
foreach( $results as $row ){
echo "<tr><td>";
echo $row['Title'];
echo "</td><td>";
echo $row['BasicTicketPrice'];
echo ('<td><a href="perf.php?id=".$row['TicketId'].""><input type="submit" name="submit"
value="Register" class="register" /></a></td>');
echo "</tr>";
}
?>
</table>
</body>
</html>

Related

Delete record in php and mysqli

l have created an application using php,html and mysql. The application can store a user's information such as id, name, bio, and date created into the database and display in html table. The id is an auto increment value which increases with every data entered by the user. The insert part of the application works fine but when l try to delete a record nothing happens. An html form is part of the code which l have intentionally decided not to include. Here is a snapshot of my code:
$records = array();
if(!empty($_POST)) {
if(isset($_POST['firstName'],$_POST['lastName'], $_POST['bio'])){
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$bio = trim($_POST['bio']);
if(!empty($firstName) && !empty($lastName) && !empty($bio)) {
$insert = $db->prepare("INSERT INTO people (firstName, lastName,
bio, created) VALUES (?, ?,?, NOW())");
$insert->bind_param('sss', $firstName, $lastName, $bio);
if($insert->execute()){
header('Location: addressbook.php');
die();
}
}
}
}
if($results = $db->query("SELECT * FROM people")){
if($results->num_rows){
while($row = $results->fetch_object()){
$records[] = $row;
}
$results->free();
}
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class = "container">
<?php
if(!count($records)){
echo 'No records found';
}
else{
?>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Bio</th>
<th>Created</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
foreach ($records as $r) {
?>
<tr>
<td><?php echo escape($r->id);?></td>
<td><?php echo escape($r->firstName); ?></td>
<td><?php echo escape($r->lastName); ?></td>
<td><?php echo escape($r->bio); ?></td>
<td><?php echo escape($r->created); ?></td>
<td>
<a onclick="return confirm('Do you want to delete the
record')" href="addressbook.php?idd=<?php echo $row['id'] ?>"
class="btn btn-
danger">Delete</a></td>
<?php
}
?>
</tr>
//My guess is the problem is with this code down here for deleting
<?php
if(isset($_POST['idd'])){
$idd = $_POST['idd'];
$results = $db->query("DELETE FROM people WHERE id=$idd");
if($results){
header('Location: addressbook.php');
}
}
?>
</tbody>
</table>
<?php
}
?>
you need to use $_GET because by default href tag sends the data with GET method.
your code should be
if(isset($_GET['idd'])){
$idd = $_GET['idd'];
$results = $db->query("DELETE FROM people WHERE id='$idd'");
if($results){
header('Location: addressbook.php');
}
}
NOTE- use prepared statement for avoiding sql injection attack
`
<?php
//database connectivity
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"<db_name>");
$idd = $_REQUEST['idd'];
$sql= "DELETE FROM people WHERE id='$idd' ";
$result = mysqli_query($con,$sql) or die(mysql_error());
header("refresh:0.1; addressbook.php");
?>`
if(isset($_GET['idd'])){
$idd = $_GET['idd'];
$results = $db->query("DELETE FROM people WHERE id='{$idd}'");
Try adding a single quote.
If it still doesn't work, please see if the $_POST is actually posting correctly.
Try $results = $db->query("DELETE * FROM people WHERE id=$idd"); instead of $results = $db->query("DELETE FROM people WHERE id=$idd"); in the delete User Function :)

PHP website search

I'm having trouble getting my php search project working properly, having followed a guide, I don't fully understand the guide/code. My search bar will allow me to search for jobs in the database, but currently it shows all jobs and filters the one you search.
Is it possible to display these jobs as links, where it will take you to another page and display the currently selected job.
Here is my current code:
<?php
require 'config.php';
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `job` WHERE CONCAT(`location`, `description`, `budget`, `duedate`,`title`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `job`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "bid4myjob");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="submit" value="Search"><br><br>
<table>
<tr>
<th>Title</th>
<th>Location</th>
<th>Description</th>
<th>Budget</th>
<th>Due date</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['description'];?></td>
<td><?php echo $row['budget'];?></td>
<td><?php echo $row['duedate'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Your problem is this line:
if(isset($_POST['search']))
There's no variable called "search" which will be submitted by your form, so its value will never be set, and this if block will never be entered. I suspect you've confused the "name" attribute which determines the variable's name in the POST array, with its value ("Search", in the case of your button). Try
if(isset($_POST['submit']))
instead.
See also my comments above about your security problems and aim to fix those a.s.a.p.

i want to make delete button [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So i start the language in this summer,and i have problem,i don't know how to make delete button,i looked lot of pages but i can't find how to make with pdo.
countryandcity.php
<?php
require 'pdo.php';
$connect=connect();
?><!DOCTYPE html>
<html>
<head>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="wrapper">
<table class="table" >
<thead>
<tr>
<th>Country</th>
<th>City</th>
<th>Image</th>
</tr>
<form action="deleteall.php" method="POST" >
<?php
$sql = connect()->prepare("SELECT * FROM countries ORDER BY country");
$sql->execute();
while($result = $sql->fetch(PDO::FETCH_ASSOC)) {
echo"<tr>";
echo"<td>".$result['country']."</td>";
echo"<td>".$result['city']."</td>";
if(!empty($result['image'])){
echo '<td><img src="images/'.$result['image'].'"/></td>';
}
else {
echo"<td>-</td>";
}
echo "<td><a href='edit.php?uid=".$result['country']."'>Edit</a></td>";
echo "<td><a href='deleteall.php?uid=".$result['country']."'>Delete</a></td>";
echo"</tr>";
}
?>
</form>
</thead>
</table>
</div>
</body>
deleteall.php
<?php
require 'pdo.php';
$connect=connect();
if(isset($_POST['delete_btn']))
?><!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<div class="form-group">
<label>Do u want to delete?</label>
</div>
<button>
<input type="submit" value="YES" name="delete_btn">
</button>
<button>
<input type="submit" name="no" value="NO">
</button>
</form>
</body>
</html>
Please help me with the sql query and php code after if(isset), i need help!
I just want to delete on row from the database.
How can I solve this?
Sorry for my bad english.
Thanks!
Here is correction of your firsts page (content in <tbody> instead of <thead>, no <form> needed, ...) countryandcity.php :
<table>
<thead>
<tr>
<th>column name...</th>
</tr>
</thead>
<tbody>
<?php
$sql = connect()->prepare("SELECT * FROM countries ORDER BY country");
$sql->execute();
if($result = $sql->fetch(PDO::FETCH_ASSOC)) {
foreach($result as $i => $item) {
extract($item);
echo "<tr><td>$country</td>";
echo "<td>$city</td>";
if(!empty($image)) {
echo "<td><img src=\"images/$image\"/></td>";
}
else {
echo "<td>-</td>";
}
echo "<td>Edit</td>";
echo "<td>Delete</td></tr>";
}
}
?>
</tbody>
</table>
</div>
</body>
</html>
And here solution for deleting your record in deleteall.php :
<?php
if(isset($_GET['delete_btn'])) {
$country = addslashes($_GET['delete_btn']);
$q = "DELETE FROM countries WHERE country = '$country'";
require 'pdo.php';
$sql = connect()->prepare($q);
$sql->execute();
}
?>
hope it will help you, you can add delete link then go this page it will delete
Edit
Delete
<?php
require 'pdo.php';
$connect = connect();
?>
<!DOCTYPE html>
<html>
<head>
<link href="style.css" type="text/css" rel="stylesheet"/>
</head>
<body>
<div class="wrapper">
<table class="table">
<thead>
<tr>
<th>Country</th>
<th>City</th>
<th>Image</th>
</tr>
<form action="deleteall.php" method="POST">
<?php
$sql = connect()->prepare("SELECT * FROM countries ORDER BY country");
$sql->execute();
while ($result = $sql->fetch(PDO::FETCH_ASSOC)) {
if (!empty($result['image'])) {
$content_image = '<td><img src="images/' . $result['image'] . '"/></td>';
} else {
$content_image = '<td>-</td>';
}
?>
<tr>
<td> <?= $result['country'] ?></td>
<td><?= $result['city'] ?></td>
<?= $content_image ?>
<td>Edit</td>
<td>Delete
</td>
</tr>
<?php }
?>
</form>
</thead>
</table>
</div>
</body>
</html>
then this is your deleteall.php
<?php
$uid = trim($_GET['uid']);
if(isset($uid)) {
$sql = "DELETE FROM countries WHERE country = ?";
$q = connect()->prepare($sql);
$response = $q->execute(array($uid));
}
?>
For the form, I'd recommend having a button that acts as the function, that way you don't accidentally lose all your data when the page loads, or anything like that. This is simply three lines of code.
<form action="deleteall.php" method="POST">
<input type="hidden" value="true" name="cameFromForm">
<button type="submit" name="confirmButton">Delete All</button>
</form>
When the button is clicked, then it will trigger the entry point of deleteall.php, which then takes the input and deletes ALL data from the table.
<?php
if(isset($_POST["cameFromForm"]) && $_POST["cameFromForm"] == "true") {
// This makes sure that the form actually sent it.
try {
$tableName = "Insert the name of your table here";
$mysqli = new mysqli(
'databaseHost',
'databaseUser',
'databasePassword',
'databaseName');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("DELETE FROM ?");
$stmt->bind_param('s', $tableName);
$stmt->execute();
$stmt->close();
$mysqli->close();
header('Location: http://afterDeltePage.com');
}
catch (Exception $e) {
print($e);
die();
}
}
else {
header('Location: http://notAuthorisedPage.com');
}
?>
Once you've finished the process, you should send the user to a page with UI. Try to separate the things you need to show the user and your processes. Also, if this is going to be public, you need to make sure that deleteall is not accessible by anyone by URL.
To do that, you need to move your file out of the wwwroot (public_html usually). There are various topics on how to do that.
PHP Forms information and PHP MySQLi information.

Export MSSQL Query To CSV File From PHP

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>

Passing data from clickable table row to detail page using PHP

I am trying to make each row in my table clickable. So when a user clicks on a row it should go to a details page containing the data from that row.
Part of my html code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
session_start();
include 'config.php';
$query_string = "SELECT * FROM tbl_User INNER JOIN tbl_Role ON tbl_User.role_id=tbl_Role.role_id";
$query = mysqli_query($con, $query_string);
?><!DOCTYPE html>
<html lang="en">
<head>
....
</head>
<body>
<table id="myTable" class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Profile Picture</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($query)){
echo "<tr>";
echo "<td>{$row['name']}</td>\n"
echo "<td>".$row['email']."</td>";
echo "<td><img class='picTable' src='plugins/images/".$row['profile_picture']."'></td>";
echo "<td>".$row['role']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
<script>
$("#myTable").on("click", "tr", function(e){
// get the value
var value = $(this).find('td:first').text();
// redirect the user with the value as a GET variable
window.location = 'user_detail.php?name=' + value;
});
</script>
</body>
My table looks like this:
When I click on a row it does redirect to the page, with the id in the url
the url for the user details page looks like this:
http://localhost:8888/challenger/user_detail.php?user_id=5
Code for the user detail page is:
<?php
session_start();
include_once 'config.php';
$qry = "SELECT * FROM tbl_User WHERE user_id = {$_GET['user_id'] "
$query = mysqli_query($con, $qry);
while($row = mysqli_fetch_array($query)){
echo $row['email'];
echo $row.['name'];
}
?>
Then I click through to the details page, it show an error (internal server error, which means for me out of experience that my php code is incorrect).
So my question is how do i display all the data (name, email, role, etc) in the details page?
I figured out how to display the data, so on the user detail page I have the following code above the DOCTYPE html tag:
<?php
session_start();
include_once 'config.php';
$id = $_GET['user_id'];
$query_string = "SELECT * FROM tbl_User INNER JOIN tbl_Role ON tbl_User.role_id=tbl_Role.role_id WHERE user_id = '$id'";
$query = mysqli_query($con, $query_string);
?>
Then in the body i read out the data like so:
<h3 class="box-title">User Details</h3>
<?php
while($row = mysqli_fetch_assoc($query)){
echo "<h1>".$row['name']. "</h1>";
echo "<h1>".$row['email']. "</h1>";
echo "<h1>".$row['role']. "</h1>";
echo "<div><img class='picTable' src='plugins/images/".$row['profile_picture']."'></div>";
}
?>

Categories