hyperlink trouble in php echo'd table - php

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.

Related

Need Assistance with following ```HTML``` Error?

I am getting the following validation error, it claims I have "misplaced non-space characters inside the table" I have tried everything and for the life of me cannot fix this error. The error is the following
Here is the PHP/HTML being used for
<?php
$title = "Alter Records";
include('includes/head.php');
include('includes/nav.php');
ini_set('display_errors', 0);
require_once('config.php');
require_once('db_class.php');
$connection = new dbController(HOST,USER,PASS,DB);
$sql = "select id,name, image,location from location";
$results = $connection->getAllRecords($sql);
//var_dump($results);
?>
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Location</th>
<th>Image</th>
<th colspan="2">Make Changes</th>
</tr>;
<?php
foreach ($results as $row){
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['location']}</td>";
echo "<td><img class='thumb' src='{$row['image']}' alt='{$row['name']}'> </td>";
echo "<td><a href=''>Update</a></td>";
echo "<td><a href='delete_record.php?id={$row['id']}'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
include('includes/footer.php')
?>
Here is the code inside validator.w3.org
↩
<!DOCTYPE html>↩
<html lang="en">↩
<head>↩
<meta charset="utf-8">↩
<title>Alter Records</title>↩
<link href="https://fonts.googleapis.com/css2?family=Quicksand&display=swap" rel="stylesheet">↩
<link href="https://fonts.googleapis.com/css2?family=Bellota+Text:ital,wght#1,300;1,400&display=swap" rel="stylesheet">↩
<link rel="stylesheet" href="css/style.css">↩
</head>↩
<body>↩
<header><h1> TOURISM VICTORIA</h1></header>↩
<nav>↩
<ul class="flex-nav">↩
<li>Home</li>↩
<li>Add</li>↩
<li>Alter</li>↩
<li>↩
<form class="search-form" action="search.php" method="get">↩
<input type="text" name="search">↩
<button type="submit">Search</button>↩
</form>↩
</li>↩
</ul>↩
</nav>↩
<table>↩
<tr>↩
<th>Id</th>↩
<th>Name</th>↩
<th>Location</th>↩
<th>Image</th>↩
<th colspan="2">Make Changes</th>↩
</tr>;↩
<tr><td>1</td><td>Melbourne ShowGrounds</td><td>Royal Melbourne Showgrounds. Ascot Vale, Victoria, Austra
Any assistance with this would be greatly appreciated. If I am still unclear, please ask for further clarification.
just seeing your last include will also result in an error, you will need to end with ;

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.

Get data of multiple columns from SQL Server using PHP

I am trying to select the data from SQL Server but only the columns stored in the variable SelectedColumns. This variable store the columns' names separated by comma from a drop Down list. For example : echo $SelectedColumns will display Country,Product,Date
I could create the header of the table by exploding the variable and use foreach. Now I want to get the data of these columns display it in the <tbody> </tbody>
Here is my php page :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ser="********";
$db="********";
$user="********";
$pass="********";
$query = 'SELECT '.$_POST['selectedColumns'].' FROM ********';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=********,1456;Database=********;Port=1456", $user, $pass);
?>
<!DOCTYPE html>
<html>
<head>
<title>table</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<?php
$row = $_POST["selectedColumns"];
$rows = explode(",",$row);
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>";
echo $r;
echo "<td>";
}
echo "</tr>";
?>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
I was trying this solution to use foreach twice
<?php
$row = $_POST["selectedColumns"];
$rows = explode(",",$row);
foreach ($dbDB->query($query) as $dataRow) {
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>" . $dataRow[$r] . "</td>"; }
echo "</tr>";
}
?>
But it's not working. Any suggestions please ? Thank you very much.

Undefined variable: records in C:\XAMPP\htdocs\display_prsc.php on line 29

I want to retrieve data from MySql table. I am using Xampp, phpMyAdmin etc... I followed this tutorial step by step: https://www.youtube.com/watch?v=IHdd02IK2Jg
But I get this error:
Notice: Undefined variable: records in C:\XAMPP\htdocs\display_prsc.php on line 29
And a warning:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in C:\XAMPP\htdocs\display_prsc.php on line 29
It just displays the column names when i run it.
<? php
//make connection
mysql_connect('localhost','root','');
//select_db
mysql_select_db('mynewdb');
$sql="SELECT * FROM new";
$records=mysql_query($sql);
?>
<html>
<head>
<title>Program Scores Table</title>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Year</th>
<th>Criteria</th>
<th>Score</th>
<tr>
<?php
while ($new=mysql_fetch_assoc($records)){
echo"<tr>";
echo"<td>".$new['py']."</td>";
echo"<td>".$new['pcrit']."</td>";
echo"<td>".$new['psco']."</td>";
echo"</tr>";
}
?>
</table>
</body>
</head>
</html>
You have a few errors in your code:
1. Wrong php opening tag
You have to remove the space in your php opening tag, e.g.
<?php
2. Weird html
Almost your entire html is wrong! I would recommend you to read a book or watch a basic html tutorial
So your entire code should look something like this:
<?php
//make connection
mysql_connect('localhost', 'root', '');
//select_db
mysql_select_db('mynewdb');
$sql = "SELECT * FROM new";
$records = mysql_query($sql);
?>
<html>
<head>
<title>Program Scores Table</title>
</head> <!-- head tag closed here -->
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Year</th>
<th>Criteria</th>
<th>Score</th>
</tr> <!-- forgot / to close the tag -->
<?php
while ($new = mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>" . $new['py'] . "</td>";
echo "<td>" . $new['pcrit'] . "</td>";
echo "<td>" . $new['psco'] . "</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
Side Notes:
1. What can be improved?
I would do some basic error checking e.g. if the connection failed and so on
Use mysqli_* with prepared statements, or PDO with prepared statements, they are much safer! (We live in 2015)
(Also if the guy in your tutorial uses mysql_*, change the tutorial!)
So that you don't only have your old code working, here your improved code:
<?php
//Database stuff
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "mynewdb";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM new");
$stmt->execute();
//Close Connection
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<html>
<head>
<title>Program Scores Table</title>
</head>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Year</th>
<th>Criteria</th>
<th>Score</th>
</tr>
<?php
while ($new = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
echo "<td>" . $new['py'] . "</td>";
echo "<td>" . $new['pcrit'] . "</td>";
echo "<td>" . $new['psco'] . "</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
2. Coding side notes
Add error reporting to the top of your file(s) which will help find errors.
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
Error reporting should only be done in staging, and never production.
Note the space in your first php tag.
You have <? php , it should be <?php
And since it seems you are starting to learn, avoid learning things deprecated. Don't use MySQL, use PDO or Mysqli.
try
<?php
//make connection
$con= mysql_connect('localhost','root','');
//select_db
$select= mysql_select_db('mynewdb',$con);
$sql="SELECT * FROM new";
$records=mysql_query($sql);
?>
<html>
<head>
<title>Program Scores Table</title>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Year</th>
<th>Criteria</th>
<th>Score</th>
<tr>
<?php
while ($new=mysql_fetch_array($records)){
echo"<tr>";
echo"<td>".$new['py']."</td>";
echo"<td>".$new['pcrit']."</td>";
echo"<td>".$new['psco']."</td>";
echo"</tr>";
}
?>
</table>
</body>
</head>
</html>
I recommend you using Prepared statements for MySQL instead of clean MySQL, it's not secure at all, and will give you problems later on.
A lille guide here.
http://www.w3schools.com/pHp/php_mysql_prepared_statements.asp
There are multiple errors in your code. But for the error, it is due to mysql_query() returns FALSE at line:
$records=mysql_query($sql);
Then, the line while ($new=mysql_fetch_assoc($records)){ cannot get the value of $records, thus produce the errors.
Other errors are:
HTML
missing DOCTYPE
missing meta charset
a missing </tr>
a misplaced </head>
be modern, use CSS to style your HTML instead of using HTML tag attributes
PHP
didn't check the return value of functions before using them
use of deprecated mysql_* functions; use PDO / MySQLi instead
extra space at <? php

Data table not working

I have a table which I populate using data from MySQL via PHP.
<table id="tab" class="table">
<thead>
<tr>
<th>Heading</th>
</tr>
</thead>
<tbody>
<?php
session_start();
$id=$_SESSION['id'];
$val=$_SESSION['val'];
if($val=="1")
{
$result = $obj->getAllVals();
}
else
{
$result = $obj->getVal($id);
}
foreach($result as $row) { ?>
<tr style="cursor:pointer" onclick="gp('<?php echo $row['name']; ?>')">
<td> <?php echo $row['name']; ?> </td> </tr>
<?php } ?>
</tbody>
</table>
I'm not able to see my data as a datatable. Here is how I'm calling Data tables:
$(document).ready( function () {
$('#tab').dataTable();
});
Here are the scripts I'm using:
<script src="static/js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="static/lib/jquery.dataTables/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="static/lib/jquery.dataTables/js/DT_bootstrap.js"></script>
<script type="text/javascript" src="static/lib/jquery.dataTables/js/datatables.responsive.js"></script>
<script src="static/js/jquery-ui.js" type="text/javascript" charset="utf-8"></script>
Are you sur the variable $result is populated?
What if you replace this:
foreach($result as $row) { ?>
<tr style="cursor:pointer" onclick="gp('<?php echo $row['name']; ?>')">
<td> <?php echo $row['name']; ?> </td> </tr>
<?php } ?>
By this :
foreach($result as $row) { ?>
<tr><td>Test</td></tr>
<?php } ?>
Does it shows a lot of "Test" cells?
If yes, then there is something wrong with getting the infos out of the "$row" variable.
If not, then there is something wrong with either the foreach loop, or with the "$obj->" calls.
You have at least one error, that is outside the
<?php ?>
body:
<tr style="cursor:pointer" onclick="gp(\''.$row['name'].'\')">
=>
<tr style="cursor:pointer" onclick="gp('<?php echo $row['name']; ?>')">
session start methode should be in first line of php file
kindly write
<?php
session_start();
?>
Try to use a while loop, instead a foreach.
while($row = mysql_fetch_array($result)) {
echo "<tr style='cursor:pointer' onclick='gp('".$row['name']."')'>
<td> ".$row['name']." </td>
</tr>";
}
I assume that there are rows in the table and as you say "The console is not throwing up any data table related errors"
in that case you may want to check the non-related errors.
if there is an error it may stop all further script execution.
you should check if this line $('#tab').dataTable(); is executed at all (you can just replace it with alert and see)
and if this is the case the problem will be solved by correcting thous errors

Categories