Should I create a table using HTML or PHP? - php

I guess it really depends on my code but if I have the following code, can I just open a HTML tag and create a table there? I find it easier to create table using HTML than using PHP. Would it be okay to add table in html or must I echo it out in PHP for the following code?
<?php
include_once 'header2.php';
if(!$_SESSION['u_uid']) {
header ("Location: index.php?display_music_forum=notlogin");
exit();
} else {
// select query drom the database to insert below in html
$admin = 1;
$sql = "SELECT * FROM display_music_forum WHERE admin = ?;";
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, "i", $admin)
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0 && $_SESSION['u_permission'] == 0) {
header("Location: header2.php?display_music_forum=nopermission");
exit();
} else {
$row = mysqli_fetch_assoc($result);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<th>category</th>
<th>Creator</th>
<th>Date Created</th>
</table>
</body>
</html>

You should not "echo" HTML with PHP. It is better to leave all the text and html outside of PHP.
In your case, in order to have better oraginized code you may do all the php work in the top of your file, and do only the loop (foreach or for) inside the html body.
For exampleQ
<?php
include_once 'header2.php';
if(!$_SESSION['u_uid']) {
header ("Location: index.php?display_music_forum=notlogin");
exit();
} else {
// select query drom the database to insert below in html
...
...
$results = YOUR DATABASE RESULTS;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<th>category</th>
<th>Creator</th>
<th>Date Created</th>
</tr>
<?php foreach ($results as $result) { ?>
<tr>
<td><?=$result['category'];?></td>
<td><?=$result['creator'];?></td>
<td><?=$result['date_created'];?></td>
</tr>
<?php } ?>
</table>
</body>
</html>

You can embed all the html tags inside PHP by using echo.
Here is an example:
$query = $db->rawQuery("SELECT last_modified,version,last_saved_by,comments from tbl_templates WHERE slug = '".$slug."' order by id desc limit 5");
$i = 1;
echo '<table class="lastmodified" temp="true" border="1" align="center" width="100%">';
echo '<tr><td align="center"><h4><b>SL No.</b></h4></td><td align="center"><h4><b>Last version modified</b></h4><td align="center"><h4><b>Last Modified Date and Time</b></h4></td><td align="center"></td><hr><td align="center"><h4><b>Last Saved By</b></h4></td><td align="center"><h4><b>Comments</b></h4></td></tr>';
foreach ($query as $row){
echo "<tr><td align='center'><h4>".$i++."</h4></td><td align='center'><h4>{$row['version']}</h4></td><td align='center'><h4>{$row['last_modified']}</h4></td><td><hr></td><td align='center'><h4>{$row['last_saved_by']}</h4></td><td align='center'><h4>{$row['comments']}</h4></td></tr>";
}
echo '</table>';

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 :)

Can't search for a specific record in database

I want to search for a specific record in database and show it on html page. I have inserted a search bar with a search button. I want to enter let's say Student Name and view the record of that student in an html table. But it's not working, It shows nothing in the table. Here is the code for search:
<?php
include("connection.php");
if (isset($_POST['search'])) {
$valueToSearch=$_POST['valueToSearch'];
$query="SELECT * FROM 'table_name' WHERE Student_Name LIKE '%".$valueToSearch."%";
$search_result=filterTable($query);
}
else{
$query="SELECT * FROM 'table_name'";
$search_result=filterTable($query);
}
function filterTable($query)
{
$connect=#mysql_connect("localhost","root","","db");
$filter_Result=#mysql_query($connect,$query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Search Record</title>
<style>
table,tr,th,td
{
border:1px solid black;
}
</style>
</head>
<body>
<form action="search.php" method="post">
<input type="text" name="valueToSearch" placeholder="ValueToSearch"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Forget any mysql_ feature. You are establishing connection to database with mysql but trying to read results with mysqli_.. Try with
<?php
include("connection.php");
if (isset($_POST['search'])) {
$valueToSearch=$_POST['valueToSearch'];
$query="SELECT * FROM 'table_name' WHERE Student_Name LIKE '%".$valueToSearch."%'";
$search_result=filterTable($query);
}
else{
$query="SELECT * FROM 'table_name'";
$search_result=filterTable($query);
}
function filterTable($query) {
$connection = new mysqli("localhost", "root", "","db");
$filter_Result = $connection->query($query)
return !$filter_Result ? null : $filter_Result;
}
?>
Then, down in your form, replace:
while ($row = $search_result->fetch_array()) {
...
...
}
Hint:
Consider about moving your connection establishment from filterTable() function to the connection.php file and use GLOBAL $connection; in the function
Moving your connection to that file will allow you to escape string at any time with $myVar = $mysqli->real_escape_string( $myVar ) which will prevent injection
escape your keywords with mysql_escape_string();, like second thing don,t use mysql* use mysqli or pdo because mysql* has been removed from php 7.*
$valueToSearch= mysqli_real_escape_string($connect,$_POST['valueToSearch']);
after that use this query
$query="SELECT * FROM table_name WHERE Student_Name LIKE '%$valueToSearch%'";
because you have syntax error if you echo it you need to get like this
SELECT * FROM table_name WHERE Student_Name LIKE 'something';
i am giving you example with mysqli paste it in connection.php
$connect=mysqli_connect("localhost","root","","db");
now your code should be
include("connection.php");
if (isset($_POST['search'])) {
$valueToSearch= mysqli_real_escape_string($connect,$_POST['valueToSearch']);
$query="SELECT * FROM table_name WHERE Student_Name LIKE '%$valueToSearch%'";
$search_result=filterTable($query,$connect);
}
else{
$query="SELECT * FROM table_name";
$search_result=filterTable($query,$connect);
}
function filterTable($query,$connect)
{
$filter_Result=mysqli_query($connect,$query);
if (!$filter_Result) {
die('query is not valid '.mysqli_error($connect));
}
else{
return $filter_Result;
}
}

Display result using IF/ELSE in PHP

I have a sample code for my problem. what i want to do is if i search for "Helloworld" then i want to inform the user that there's no data matched based from their inputted data. Im thinking if can i use if else statement to do a validation if the data inputted didn't matched any rows and if the inputted data matched some rows. As i visualized the solution for this problem i think this method is the solution but i don't how can i do this. i think the solution is to put if else condition here's my code how i thought about it
if the result of search is not nothing then it will show the result then if nothing then the message will appear "no data matched"
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `users`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$filter_Result = mysqli_query($connect, $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="search" value="Filter"><br><br>
<?php
if($result_validation != ''){
?>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
<?php
}else{
echo "no data matched";
}
?>
</form>
</body>
</html>
I see no point in displaying the entire table inside the form, you should display it somewhere outside of the form. Having said that, $result_validation variable is undefined, you need to use $search_result in your code.
And as per your question, use mysqli_result::$num_rows to check number of rows returned from the SELECT query.
if($search_result->num_rows){
// display table
}else{
echo 'no data matched';
}

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.

hyperlink trouble in php echo'd table

I"m having trouble with my code hopefully someone can help.
I'm trying to call information using "php echo" to display information in table form and it works except for the links which doesn't recognize the $id. If I don't put it in the table form it works fine but it is not aesthetically appealing.
Any suggestions would be greatly appreciated!
<?php
session_start();
if(!isset($_SESSION['name'])){
header("location: ../index.php");
exit();
}
// Script Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once("../scripts/connect.php");
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete messages with ID of ' . $_GET['deleteid'] .'? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysql_query("DELETE FROM `mystore`.`messages` WHERE `messages`.`id` = '$id_to_delete' LIMIT 1") or die (mysql_error());
}
$messages = "";
$sql = mysql_query("SELECT * FROM messages ORDER BY msg_date DESC LIMIT 20");
$count = mysql_num_rows($sql);
if($count > 0){
while($row = mysql_fetch_array($sql)){
echo '<tr>';
echo '<td>'.$row['msg_name'].'</td>';
echo '<td>'.$row['msg_email'].'</td>';
echo '<td>'.$row['msg_subject'].'</td>';
echo '<td>'.$row['msg_date'].'</td>';
echo '<td>Reply</td>';
echo '<td>Delete</td>';
echo '</tr>';
}
}else{
$messages = "<b>There are no messages in the database at this moment</b>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Admin Messages</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="style/forms.css" media="screen">
<link rel="stylesheet" href="style/main.css" media="screen">
</head>
<body>
<div id="main_wrapper">
<?php include_once("templates/tmp_header.php"); ?>
<?php include_once("templates/tmp_nav.php"); ?>
<section id="main_content">
<h2 class="page_title">Messages</h2>
<br/>
<table width="730" cellspacing="0" cellpadding="3" border="1">
<tr>
<td align="center" width="100">From</td>
<td align="center" width="300">Email</td>
<td align="center" width="300">Subject</td>
<td align="center" width="100">Date</td>
<td align="center" width="100">Actions</td
></tr>
<?php echo $messages; ?>
</table>
</section>
<?php include_once("templates/tmp_aside.php"); ?>
<?php include_once("templates/tmp_footer.php"); ?>
</div>
Please change
echo '<td>Delete</td>';
to
echo "<td><a href='admin_messages.php?deleteid=$id'>Delete</a></td>";
when trying to print out a variable the main string has to be wrapped in double quotes.
If you want to interpolate variables in PHP, you need to use double quotes. echo '$id' will literally print $id, whereas echo "$id" will print the value of the variable. However, I would recommend an alternative approach. Don't use PHP where it isn't needed. There's no need to use echo so much.
I would change the contents of your loop to this:
?>
<tr>
<td><?=$row['msg_name']?></td>
<td><?=$row['msg_email']?></td>
<td><?=$row['msg_subject']?></td>
<td><?=$row['msg_date']?></td>
<td>Reply</td>
<td>Delete</td>
</tr>
<?php
The <?=$id?> is shorthand for <?php echo $id?> and is supported by default in PHP versions >=5.4.0. You can also use it in previous versions if you enable short_open_tags.
As stated in the comments, you should really be using mysqli functions, as mysql functions are deprecated.

Categories