I have news_Category and news table, here every news comes under one category,so before deleting new_category I want to display user a msg that child news exists in this category so u are not allowed to delete, If there are no child news than a confirm alert to user that "do u really want to delete".If he confirms the news category gets deleted.
HTML STUFF
<?php echo "<a style='color:red;''
href='delete.php?delete=$values[category_id]&
img=$values[category_image]'><i class='fas fa-trash-alt'></i></a>"; ?>
if ($_GET['msgError']) {
echo "<script>alert('First Delete The News Than Category');</script>";
}
if ($_GET['msg']) {
?>
<?php
}
?>
DELETE.PHP
if (isset($_GET['delete'])) {
$id= $_GET['delete'];
$img=$_GET['img'];
$obj=new commands();
$obj->delete_category($id,$img);
}
Delete Function
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
I am not able to make to logic here, how can I check whether the child news exists so i can display error msg and if there is no child news how to show confirm alert to allow delte
You need to check to see if the result is empty.
Something like this:
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($result)) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
Edit due to extra details request
On the front end you just need to display the GET msgError like this:
<?php isset($_GET['msgError']) ? echo url_decode(base64_decode($_GET['msgError'])) : '' ?>
Where you want to show the message text.
Related
so i have webpage called news.php where i show all the website news from database.
i want to make new page to view only single news by news id from database, for example the page is shownews.php
so this is my index.php
<?php
include('config/webconf.php');
include('includes/head.php');
include('includes/nav.php');
include('includes/body.php');
include('includes/foot.php');
?>
my body.php contain this to modify the url to /?p=pagename :
<?php
if(isset($_GET['p'])) {
if(file_exists("pages/" . $_GET['p'] . ".php")) {
include("pages/" . $_GET['p'] . ".php");
}else{
include("pages/notfound.php");
}
}else{
include("pages/info.php");
}
?>
news.php (show all news)
mysqli_select_db($conn, $webdb);
$stmt = $conn->prepare("SELECT id,title, content, author FROM news");
$stmt->execute();
$stmt->bind_result($newsid, $title, $content, $author);
$stmt->store_result();
if($stmt->num_rows > 0) {
while($stmt->fetch()) {
echo $title." (<a href='/?p=shownews?id=".$newsid."' target='_blank'>view</a>)";
}
}
so in shownews.php i want to get the id from $newsid, but i think cannot get it because of the url is /?p=shownews?id=1 where the url name function will not find shownews?id=1 (page not found)
so i tried to change /?p=shownews to pages/shownews.php?id=$newsid :
mysqli_select_db($conn, $webdb);
$stmt = $conn->prepare("SELECT id,title, content, author FROM news");
$stmt->execute();
$stmt->bind_result($newsid, $title, $content, $author);
$stmt->store_result();
if($stmt->num_rows > 0) {
while($stmt->fetch()) {
echo $title." (<a href='pages/shownews.php?id=".$newsid."' target='_blank'>view</a>)";
}
}
now i can get $news id by $_GET function in shownews.php, but the website styles is gone like div/background etc.
my question is, can i get the news id in page shownews.php without changing the url name function?
I'm trying to create a "Like" button for some articles that I'm printing out from my database. But I'm stuck.
I get to the point where I have posted my vote from the jQuery and I get an empty VAR_DUMP.
And in my OOP class I'm not sure how to print out the votes when I got them to save in the database.
Here's my code
HTML
<?php
// IF theres is a id in adress field
//if(isset($_GET['id'])) {
$page = new CMS();
$gp = $page->getPage();
foreach ($gp as $sp) {
//var_dump($sp);
echo "<div class='pub'>";
echo "<h4 class='pub-headline'>" . $sp['title'] . "</h4>";
echo "<article class='pub_art'>" . $sp['content'] . "</article>";
echo "<p class='pub_created'>" . $sp['created'] . "</p>";
echo "<p class='pub_created_by'>". $sp['writer'] ."</p>";
echo "<button class='show'>Show</button>";
echo "<button class='noshow'>Hide</button>";
echo "<button class='btn-like'>Like</button>"; // Here is my button
echo "</div>";
}
?>
jQuery
/* --------------------Selecting article----------------------*/
// Calling for the method - likes
$(".btn-like").on("click", like);
function like(e) {
e.preventDefault();
// Declaring variables
var id=$(id).val();
var likes=$(".btn-like").val();
console.log('Click Click..');
$.post('classCalling4.php', {
id: id,
likes: likes },
function(data){
console.log(data);
});
}
PHP
var_dump($_POST); // ***** This VAR_DUMP is getting back to me empty
if(isset($_POST['id'])) {
//echo "rätt...";
$id = $_POST['id'];
$likes = $_POST['likes'];
$id = intval($id);
$likes = intval($likes);
$ul = new updateLikes();
if($ul->updateLikes($_POST['id'], $_POST['likes'])) {
echo "Created";
}
else {
} echo "noooo";
}
?>
And finally my OOP class, that is not complete because I'm stuck.
public function updateLikes($id, $likes) {
$stmt = $this->db->prepare('UPDATE pages SET likes = likes+1, WHERE id = $id');
$stmt->bind_param("ii", $likes, $id);
if($stmt->execute()) {
echo "win";
} else {
echo "lost";
}
}
At least your OOP class have some errors:
$stmt = $this->db->prepare('UPDATE pages SET likes = likes+1, WHERE id = $id');
$stmt->bind_param("ii", $likes, $id);
Should be:
$stmt = $this->db->prepare('UPDATE pages SET likes = likes + :likes, WHERE id = :id');
$stmt->bind_param(":likes", $likes);
$stmt->bind_param(":id", $id);
or if the meaning is to increase likes only by one, then:
$stmt = $this->db->prepare('UPDATE pages SET likes = likes + 1, WHERE id = :id');
$stmt->bind_param(":id", $id);
If var_dump doesn't return anything, then there might be error in the PHP code (causes error code 500 and depending on PHP settings PHP might return blank page)
Hey guys so i really have a problem in php and i have been working on it for like an hour and i can get it to work. So in my database i have two tables:
usuarios and menus
So each user have a menu assigned like this:
usuarios
id email ....... menus
1 email ...... 1,2,3,4
where 1,2,3,4 is text that i will explode and convert it into an array so latter i can get the menus checking the menu id's.
menus
id url .....
1 profile ..........
2 messages ..........
3 log out ..........
4 support ..........
I dont know why it is not working, please help.
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));}
// Checks the user id from his session (session has been already started in headers)
if($stmt->rowCount() > 0){
$row = $stmt->fetch();
$menus = $row['menus'];
//Gets the menus
$menus = explode(",", $menus);
//Converts the text into an array.
$i = 0;
$menusize = sizeof($menus);
//Checks how big is $menus array
$menusize = $menusize -1;
//This is because $i=0 and not 1
while ($i == $menusize) {
try{
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
$stmt->execute(array(':menus'=>$menus[$i]));
$row = $stmt->fetch();
if ($section==$row['url']) {
echo '<li class="liselected"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}else{
echo '<li class="menuelement"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
$i++;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Here is the problem, in this while
} else {
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}else{
header("Location:index.php");
}
?>
I have checked and what happends is that $i doesnt seems to be incrementing, i have been working on it but nothing seems to do it.
Thank you all for your support!
You should do it a little bit differently altogether, like storing the menu's in different rows but for now:
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
# When you set the $_SESSION['id'] and you're sure it's sanitized you don't have to prepare a query. Instead execute it directly.
# Preparing is useful for user submitted data or running the same query more then once with different values (seen below)
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
// This part of the code does not match your description of your database.
$row = $stmt->fetch();
$menu = explode(",", $row['menus']);
// end
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
try{
foreach($menu as $value){
$stmt->execute(array(':menus'=>$value));
$row = $stmt->fetch();
$css_class = ($section == $row['url']) ? 'liselected' : 'menuelement';
echo '<li class="'.$css_class.'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
} else {
header("Location:index.php");
}
?>
Please note that I only prepared the query once, this is the proper way to do it. Preparing takes server performance, but once prepared you can rebind the values.
Also, I changed the loop to a foreach loop, easier to maintain.
There where also some bracket issues in the code, my advice always code in the same way so these issues are easy to spot.
I've almost finished my project but I'm stuck on a small problem I'm hoping to get help with. This is my first PHP/mysqli project and I'm still very "green". Any help is much appreciated.
I have been able to successfully upload and delete images from my database, however I can't seem to get the unlink command to delete the images from my server.
Please find below the code I am using in the background (hotel-imgdelete.php):
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete image from server
$path = "../hotels/";
$image = "name";
unlink($path.$image);
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}
?>
This is the code I am using to view and select the images to delete
(delete-hotel-images.php)
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM hotels ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
$row->id;
echo "<div id='partner'><img src='hotels/" . $row->name . "'></a><br><br>";
echo "<center><a href='#' onclick='delete_user(". $row->id . ")'>Delete</a></center></div>";
}
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
I'm not entirely sure what your filesystem looks like, or what the file is supposed to be, but it looks like you're trying to delete "../hotels/name", since $image is set to the string "name".
I'm assuming this wasn't intentional so that could be the problem there. If, however, you are trying to delete a directory (since it appears to have no file extension) you will need to use "rmdir" and not "unlink".
How are the images laid out on your filesystem?
sorted
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
if ($stmt = $mysqli->prepare("SELECT id, name FROM hotels WHERE id=?"));
{
$stmt->bind_param("i", $id);
$stmt->execute();
}
$stmt->bind_result($id, $name);
$stmt->fetch();
$path = "../images/hotels/";
$image = $name;
unlink($path.$image);
$stmt->close();
include_once 'db_connect.php';
include_once 'functions.php';
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}
I want to delete columns in my sql, which is going with succes. But there is another problem, I need to solve. I've tried and checked here around. All with any kind of succes I will try to explain my problem.
I've a member system where you can add your content, edit you submitted content and now I'm creating to delete your content. My script can delete now post which are created by the same user as logged in. For example my account is called Bobby and someone is called Alex I cannot delete the content of Alex only mimes, thats what I want.
For example my content link of bobby : category.php?nameID=cat2&id=22 And the delete link is deletepost.php?id=22
EX. content link Alex:
category.php?nameID=cat2&id=23 And the delete link is deletepost.php?id=23
When I'm logged in as Bobby and I go to deletepost.php?id=23 and receive a message like You cannot delete this content!
And When I go to mimes deletepost.php?id=22 I need to receive a message like: Your content has been delete succesfully!
I'm only receive NO!
<?php
$user = new User();
if (isset($_GET['id'])) {
$id = mysql_real_escape_string($_GET['id']);
if(!$user->isLoggedIn()) {
Redirect::to('index.php');
}
if($user->isLoggedIn()) {
$pakuser = $user->data()->username;
$sql = mysql_query("DELETE FROM post
WHERE post.id = '$id' AND post.add = '$pakuser'")
or die(mysql_error());
if (!$sql) {
echo 'NO';
}
if ($sql) {
echo 'YES';
}
}
}
?>
Beside from the possible sql injections in your code, you can try this format for a delete query to determine the mistake:
<?php
$sql = "
DELETE FROM
post
WHERE
post.id = ".$id." AND post.add = '".$pakuser."'
";
if(!$res = mysql_query($sql))
{
trigger_error(mysql_error().'<br />In query: '.$sql);
}
elseif(mysql_affected_rows() == 0)
{
echo 'No records Deleted. <br />Query: '.$sql;
}
else
{
echo 'There are '.mysql_affected_rows().' records deleted.';
}
?>
Are you also sure that post.add is the username?