Delete PDO OOP Problems - php

Good day everyone.
I totally need your help.I am pretty new to oop & pdo and I am having problems with my delete function. The item will not be delete whenever I click the delete button. It seems like I can't call the id. I just don't know what to do. Please help me solve this problem.
Here is my code.
For the class(codex):
public function deleteData($id,$table)
{
$q = "DELETE FROM $table WHERE id = :id";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':id'=>$id));
}
For the UI and the page where I call the id:
<?php
include_once "../styles/header-menu-out.php";
include_once "dbconnection.php";
function __autoload($class){
include_once("../main/".$class.".php");}
$code = new codex("localhost","library_books","root","" );
$books = $code->showData("book_info");
if(isset($_REQUEST['id'])){
if($code->deleteData($_REQUEST['id'],"book_info")){
echo "<script type='text/javascript'>
alert('Book Information have been deleted.');
window.location='bookDeleteUI.php';
</script>";
}}
?>
<html>
<head><link rel="stylesheet" type="text/css" href="../styles/library_style.css"></head>
<title>Book-A-Holic: Delete & Update Books</title>
<body><br /><center>
<div id="content"><div class="echoname"><br/><br/><b><h2>Book Settings</h2></b><br/></div>
<table id="tablecolor" class="echoname" border="1">
<td>ID</td>
<td>Title</td>
<td>Author</td>
<td>ISBN</td>
<td>Publisher</td>
<td>Language</td>
<td>Genre</td>
<td>Quantity</td>
<td>Availability</td>
<td>Queue</td>
<td><center>Settings</center></td>
<?php
echo "<pre>";
foreach ($books as $book)
{
echo "<tr>";
extract($book);
echo "<td>".$id."</td>";
echo "<td>".$title."</td>";
echo "<td>".$author."</td>";
echo "<td>".$isbn."</td>";
echo "<td>".$publisher."</td>";
echo "<td>".$language."</td>";
echo "<td>".$genre."</td>";
echo "<td>".$quantity."</td>";
echo "<td>".$availability."</td>";
echo "<td>".$queue."</td>";
?>
<td><button class="btn"><a href="bookUpdateUI.php?update=$id" >Edit</a></button>
<button class="btn">Delete</button></td>
<?php echo "</td>";
}
echo "</pre>";
?>
</table><br />
</div></center>
</body>
</hmtl>
<?php include_once "../styles/footer-admin.php"; ?>

Looks like you've almost got it and well done on using PDO with parametized queries. The problem is that you're not outputting the $id through the php interpreter. You need to do this:
<button class="btn">Delete</button></td>

Related

Displaying MySQL output in PHP as rows rather than columns

Good afternoon all :)
I would like to display my MySQL output on a PHP page as rows rather than columns for easier mobile viewing and scrolling (so the user can just scroll down the data instead of across).
I'd read about pivots and transposing but wasn't sure what was the most appropriate way to transform the return data output on the webpage. Please can you advise on what is best to use? It looks like it's easier to do it in PHP rather than MySQL?
I'm using a standard post form, connection PDO, isset, thead, php echo td and th etc.
My current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<h1>Find people</h1>
<form method="post">
<label for="people">Enter person</label>
<input type="text" id="people" name="people">
<input type="submit" name="submit" value="View Results">
</form>
<?php
//error_reporting(-1);
//ini_set('display_errors', 'On');
if (isset($_POST['submit'])) {
try {
require "./config.php";
require "./common.php";
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT *
FROM Basics
WHERE UniqueID = :people";
$people = $_POST['people'];
$statement = $connection->prepare($sql);
$statement->bindParam(':people', $people, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php
if (isset($_POST['submit'])) {
if ($result && $statement->rowCount() > 0) { ?>
<h2>Results</h2>
<table>
<?php echo '<table border="1">';?>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo escape($row["Field 1"]); ?></td>
<td><?php echo escape($row["Field 2"]); ?></td>
<td><?php echo escape($row["Field 3"]); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<br>No results found for <?php echo escape($_POST['people']); ?>, as the data has likely not been added yet.
<?php }
} ?>
<!--
<?php if (isset($_POST['submit']) && $statement) { ?>
<?php echo escape($_POST['people']); ?> successfully found.
<?php } ?>
-->
</body>
</html>
My current output:
Current example output:
Output example I would like:
Similar to this example I found (can be in a table or not like below):
Update edit:
Looks like I just needed to use ul and li!
<ul>
<li><b>Name:</b> <?php echo escape($row["Name"]); ?></li>
</ul>
I would use array_walk() to loop over the rows and within that loop, start the tr-tag, loop over the values of the current row, output them as td-elements, exit the td-loop, output the closing tr-tag and exit the tr-loop. Not that fancy solution but simple.
Looks like I just needed to use ul and li!
<ul>
<li><b>Name:</b> <?php echo escape($row["Name"]); ?></li>
</ul>

Loading a PHP page into a HTML div

So I am currently trying to create a portion of my website that fetches a mySQL table. I wrote the php to fetch the data, create a table, and print out the table in a separate php file named display.php. Now i am trying to load it into a div on my html page but for some reason it is not working. I am using XAMPP and php is working as my login page works. Here is the code:
HTML: (I have tried both include and require)
<html>
<body>
<div id="display" class="myCustom1">
<?php require('display.php'); ?>
</div>
<div id="display" class="myCustom1">
<?php include("display.php"); ?>
</div>
</body>
</html>
PHP: (if i run just the php page it creates the table)
<?php
$servername = "localhost";
$username = "test";
$password = "test";
$database = "data1";
//create connection & access DB
$connect = mysqli_connect("$servername","$username","$password","$database");
//if error, display error
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($connect,"SELECT * FROM data1enter");
echo
"
<table border='1'>
<tr>
<th>Song</th>
<th>Author</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['song'] . "</td>";
echo "<td>" . $row['author'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($connect);
?>
You are using <?php ?> tags in the html file, Change the extension of the file containing the below code to .php from .html and you will be able to use include function.
<html>
<body>
<div id="display" class="myCustom1">
<?php require('display.php'); ?>
</div>
<div id="display" class="myCustom1">
<?php include("display.php"); ?>
</div>
</body>
</html>
Also make sure the include path is correct.
Hope it helps !
Display should be blade template ..
#include('display')
Give path to display template
Just put the php in a function. Then you can do this:
<html>
<body>
<?php require_once('display.php'); ?>
<div id="display" class="myCustom1">
<?php render(); ?>
</div>
</body>
</html>
<?php
function render()
{
//YOUR PHP CODE
}
?>

Array gets emptied when i try to add new stuff to it (PHP)

I am trying to add stuff into an array after every click a user makes on a category but for some reason it keeps replacing everything in the array. I can't figure out where I am going wrong. I've tried 'googling' it and every example i find looks similar to what i have written. Please Help!
these functions are store in core.php
function getStoreBacktrace($cat) {
include("config.php");
$backtrace = array();
if ($cat != 0) {
array_push($backtrace, $cat);
}
if (count($backtrace != 0)) {
foreach($backtrace as $c){
echo getBackCatName($c);
}
}
print_r($backtrace); // Put this to see what output is
}
function getBackCatName($c) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `id`="'.$c.'"';
$r_query = mysql_query($query);
$result = mysql_fetch_array($r_query);
echo ' > '.$result['name'].'';
}
this function prints out a list of links the user can click on
function getStoreCat($cat) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `main`="'.$cat.'" ORDER BY `name` ASC';
$r_query = mysql_query($query);
echo '<ul>';
while ($result = mysql_fetch_array($r_query)) {
echo '<li>';
echo ''.$result['name'].'';
echo '</li>';
}
echo '</ul>';
}
and it gets called in store.php
<?php
include("config.php");
include("core.php");
$backtrace = array();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title><?php echo getSiteTitle().' :: '.getSiteSlogan(); ?></title>
</head>
<body>
<table width="100%">
<tr>
<td colspan="2">
<!-- Backtrace -->
Home
<?php echo getStoreBacktrace($cat, $backtrace); ?>
</td>
</tr>
<tr>
<td>
<!-- Categories -->
<table>
<tr>
<td><?php echo getStoreCat($cat); ?></td>
</tr>
</table>
</td>
<td>
<!-- Products -->
<table>
<tr>
<?php echo getStoreProducts($cat); ?>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
now everytime a user clicks on a link that is made from the function getStoreCat($cat) it refreshes the page with new links to click on and new products to show depending on what $cat they chose. i want to push the $cat to the $backtrace array.
Right here:
$backtrace = array();
You are effectively resetting the array for each call to getStoreBacktrace().
EDIT:
Thanks for fixing your question. Now it's clear that the issue is you need to make $backtrace persistent through multiple page views. Do this using sessions:
Page template
<?php
session_start(); // enable sessions
include("config.php");
include("core.php");
?>
<!DOCTYPE html>
etc...
Function definition
<?php
function getStoreBacktrace($cat) {
include_once("config.php"); // use include_once() to prevent possible errors
if (!isset($_SESSION['backtrace']))
$_SESSION['backtrace']= array();
if ($cat != 0) {
array_push($_SESSION['backtrace'], $cat);
}
...
Everytime you call getStoreBacktrace you instantiate a brand new array in $backtrace.

Display wrong information with the good row value

I have a problem with the code below. In fact, it's supposed to show the information of a table, where the MomentEvent value match with the row requested. The only problem, is that sometimes, it show the information of a complete diffrent row! And I don't have any idea why! Does the problem come from my code?
And in my table, the information are placed in order, so they are always added one after an other.
<?php
include('base.php');
?>
<?php
if(isset($_GET['MomentEvent']))
{
$MomentEvent = intval($_GET['MomentEvent']);
$dn = mysql_query("select Ordre, Confidentialite, ID, TitreEvent, DescriptionEvent, LieuEvent from users_event where MomentEvent=$MomentEvent");
if(mysql_num_rows($dn)>0)
{
$dnn = mysql_fetch_array($dn);
?>
This is the profile of "<?php echo htmlentities($dnn['TitreEvent']); ?>" :
<table style="width:500px;">
<tr><td>
<?php
if($dnn['avatar']!='')
{
echo '<img src="'.htmlentities($dnn['avatar'], ENT_QUOTES, 'UTF-8').'" alt="Avatar" style="max-width:100px;max-height:100px;" />';
}
else
{
echo 'This user dont have an avatar.';
}
?>
</td>
<td class="left"><h1><?php echo ($dnn['TitreEvent']); ?></h1>
Email: <?php echo htmlentities($dnn['DescriptionEvent']); ?><br />
<a href=*****.php>Retour.</a>
</tr>
</table>
<?php
}
else
{
echo 'Sorry, any event found';
}
}
else
{
echo 'The user ID is not defined.';
}
?>
</body>
</html>
you have missed </td> in your code.
and use echo $dnn['TitreEvent']; without parenthesis
try this
<td class="left"><h1><?php echo $dnn['TitreEvent']; ?></h1>
Email: <?php echo htmlentities($dnn['DescriptionEvent']); ?><br />
<a href=*****.php>Retour.</a>
</td>
^^----you missed this
EDIT:
Ithink you have many result returned from your sql and you need to specify more in your query .
like that
where MomentEvent=$MomentEvent AND user = $theUser
Now all works fine with these changes:
$MomentEvent = $_GET['MomentEvent'];
$sql = "select ID, TitreEvent, DescriptionEvent, LieuEvent from users_event where MomentEvent='$MomentEvent'";
$dn = mysql_query($sql);

PHP Combining search function with pagination

So I'm trying to make a page where i can display results from my database table. You should be able to search and there should be some pagination as there are thousands of results.
I've managed to make a page which just has the search, and works perfect. So now i need to know how would would integrate some pagination into that.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container">
<form action="" method="get">
<input type="text" name="search" id="search" placeholder="Search" />
<input type="submit" />
</form>
<?php include 'process.php'; ?>
</div> <!-- /container -->
<script src="js/jquery.js"></script>
<script src="js/script.js"></script>
</body>
</html>
process.php
<?php include 'dbconfig.php'; ?>
<?php include 'connect.php'; ?>
<?php
$search = $_GET['search'];
$result = mysql_query("SELECT * FROM oantkb WHERE Name LIKE '%$search%' ORDER BY `INDEX` DESC");
echo '<table class="table">';
echo '<thead>';
echo '<tr>';
echo '<th>#</th>';
echo '<th>Pic</th>';
echo '<th>Name</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = mysql_fetch_assoc($result)) {
$pic = $row['Pic'];
$name = $row['Name'];
echo '<tr>';
echo '<td>#</td>';
echo '<td><img src="'.$pic.'" height="50" width 50"></td>';
echo '<td>'.$name.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
Right now it works like it should. When i search it will say index.php?search=banana, but i need some pagination added so it will say for example index.php?search=banana&?page=2. Or something along those lines. Hope it makes sense...i'm a php newb :)
Include at the end of your sql query the following:
$resultsPerPage=10;
$page = ($_GET["page"]-1)*$resultsPerPage;
$query = $query." LIMIT $page,$resultsPerPage";
mysql_query($query);
By the way the mysql_ library is deprecated in favor of mysqli.
Also the above is susceptible to sql injection attacks because $_GET["page"] isn't first sanitized, but for simplicity I did it this way.
This assumes a paging scheme that starts at 1.
i've been using Pear Pagination for a long time. you can try it.
here is a good tutorial for setting it up
Simple Pagination in PHP tutorial
a good thing to add is clean your variable before using them in your query.

Categories