PHP Multiple CheckBox Delete - php

I am having a very hard time solving my problem with the multiple checkbox delete. Can someone direct me to the solution? What is supposed to happen here is that the user can tick the boxes and click a delete button to delete the ticked ones. Unfortunately, my code doesn't seem to work; can you point me in the right direction?
<div id="container" class="page">
<img id="disclaimer" class="page" src="images/DISCLAIMER.png" alt="" />
<img id="logo" class="page" src="images/MI-LOGO.png" alt="" />
<div id="videoContainer" class="page">
<video id="video" controls>
<source src="video/animationTest.m4v" />
</video>
</div>
<div id="etc" class="page">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<textarea name="textPost" id="textPost">
</textarea>
<input type="submit" name="btnPost" id="btnPost" value="Post" />
<div id="displayOpacity">
<input type="text" name="display" id="display" value="0" />
</div>
<input type="submit" value="Delete" name="btnDelete" id="btnDelete" />
</div>
<div id="postItDiv" class="page">
<?php
$cxn = mysqli_connect('localhost','root','root','TimePost') or die(mysqli_error());
$selectQuery = "SELECT PostID, ClientName, VideoName, PostTime, Post, Date FROM tblTimePosts";
$selectResult = mysqli_query($cxn,$selectQuery) or die(mysqli_error());
while($row = mysqli_fetch_assoc($selectResult))
{
$postz = $row['Post'];
$timez = $row['PostTime'];
$idNoz = $row['PostID'];
echo '<div id="post1"><p class="postParagraph">Post ID No.'.$idNoz.'<br />'.$postz.' at '.$timez.' seconds mark</p><input type="checkbox" name="checkbox[]" id="checkbox[]" value="'.$idNoz.'"</input></div>';
}
if ($_POST['btnPost'] == "Post") {
$toPost = $_POST['textPost'];
$date = date("y-m-d");
$postTime = $_POST['display'];
$postTime = floor($postTime);
$insertQuery = "INSERT INTO tblTimePosts VALUES ('','Mimagazine Asia','Chelsea','$postTime','$toPost','$date')";
$insertResult = mysqli_query($cxn,$insertQuery) or die(mysqli_error());
$query = "SELECT PostID, ClientName, VideoName, PostTime, Post, Date FROM tblTimePosts";
$result = mysqli_query($cxn,$query) or die(mysqli_error());
while($row = mysqli_fetch_assoc($result))
{
$post = $row['Post'];
$time = $row['PostTime'];
$idNo = $row['PostID'];
echo '<div id="post1"><p class="postParagraph">Post ID No.'.$idNo.'<br />'.$post.' at '.$time.' seconds mark</p><input type="checkbox" name="checkbox[]" id="checkbox[]" value="'.$idNo.'"</input></div>';
}
}
else if($_POST['btnDelete'] == "Delete")
{
$tbl_name = 'tblTimePosts';
foreach ($_POST['checkbox'] as $id => $value)
{
$sql = 'DELETE FROM `'.$tbl_name.'` WHERE `PostID`='.(int)$id;
$resulta = mysqli_query($cxn,$sql);
if ($resulta > 0) {
echo "success";
}
else
echo "fail";
}
header('Location: videoJudge.php');
}
?>
</form>
</div>
<span id="copyright" class="page">Copyright © 2011<span style="color:#00AEEF;">mi</span>magazine.asia</span>
<span id="comment" class="page" style="color:#00AEEF;">comment/s</span>
<span id="download" class="page">(Right-click to download video)</span>
</div>

This HTML:
echo '<div id="post1"><p class="postParagraph">Post ID No.'.$idNoz.'<br />'.$postz.' at '.$timez.' seconds mark</p><input type="checkbox" name="checkbox[]" id="checkbox[]" value="'.$idNoz.'"</input></div>';
should be:
echo '<div id="post1"><p class="postParagraph">Post ID No.'.$idNoz.'<br />'.$postz.' at '.$timez.' seconds mark</p><input type="checkbox" name="checkbox[]" id="checkbox[]" value="'.$idNoz.'" /></div>';
This query on else if($_POST['btnDelete'] == "Delete") should be:
$sql = 'DELETE FROM `'.$tbl_name.'` WHERE `PostID`='.(int)$value;

Related

Populating checkboxes from database using PHP - only last option is getting checked

I am trying to populate checkboxes with the data from my mysql database but for some reason only the last checkbox is being checked (for example if automotive, carpentry and hand tools should be checked, only hand tools is being checked) and I can't figure out why. The mysql statement is running correctly and giving me the correct information. Here is the relevant code.
<?php
require_once('../../private/initialize.php');
require_login();
if(!isset($_GET['id'])) {
redirect_to(url_for('/members/show_member_tools.php'));
}
$id = $_GET['id'];
if(is_post_request()) {
// Handle form values sent by new.php
$tool = [];
$tool['tool_ID'] = $id;
$tool['serial_number'] = $_POST['serial_number'] ?? '';
$tool['tool_name'] = $_POST['tool_name'] ?? '';
$tool['tool_description'] = $_POST['tool_description'] ?? '';
$tool['tool_picture'] = $_POST['tool_picture'] ?? '';
$category =[];
$category = $_POST['category_ID'];
$result = update_tool($tool, $category);
//get info for checkboxes
global $db;
if($result === true) {
$_SESSION['message'] = "The tool has been updated sucessfully";
redirect_to(url_for('/members/show_tool.php?id=' . $id));
} else {
$errors = $result;
}
} else {
$tool = find_tool_by_id($id);
if(isset($_GET['id'])){
$id=$_GET['id'];
$sql = "select category_name from category INNER JOIN tool_category ON category.category_ID = tool_category.category_ID where tool_category.tool_id=$id";
$query = mysqli_query($db, $sql);
while($row=mysqli_fetch_array($query)) {
// $str = "";
$str = $row['category_name'];
echo $str;
if (strpos($str , "automotive")!== false){
$checked1 ="checked";
echo "made it to automotive";
} else {
$checked1 ="";
}
if (strpos($str , "carpentry")!== false){
$checked2 ="checked";
echo "made it to carpentry";
} else {
$checked2 ="";
}
if (strpos($str , "home maintenance")!== false){
$checked3 ="checked";
echo "made it to home maintenance";
} else {
$checked3 ="";
}
if (strpos($str , "plumbing")!== false){
$checked4 ="checked";
} else {
$checked4 ="";
}
if (strpos($str , "yard and garden")!== false){
$checked5 ="checked";
} else {
$checked5 ="";
}
if (strpos($str , "hand tools")!== false){
$checked6 ="checked";
} else {
$checked6 ="";
}
}//end while loop
} //end if
} //end else
$tool_set = find_all_tools();
$tool_count = mysqli_num_rows($tool_set);
mysqli_free_result($tool_set);
?>
<?php $page_title = 'Edit Tool'; ?>
<?php include(SHARED_PATH . '/header.php'); ?>
<div id="content">
<div class="center">
« Back to My Tools
<h2>Edit Tool</h2>
</div>
<?php echo display_errors($errors); ?>
<form action="<?php echo url_for('/members/edit_tool.php?id=' . h(u($id))); ?>" method="post">
<fieldset class="form">
<img src ="<?php echo h($tool['tool_picture']); ?>" alt="<?php echo h($tool['tool_picture']); ?>"width="150"><br>
<label for="serial_number">Serial Number</label><br>
<input type="text" name="serial_number" value="<?php echo h($tool['serial_number']); ?>" ><br>
<label for="tool_name">Tool Name</label><br>
<input type="text" name="tool_name" value="<?php echo h($tool['tool_name']); ?>" ><br>
<label for="tool_description">Tool Description</label><br>
<input type="text" name="tool_description" value="<?php echo h($tool['tool_description']); ?>" ><br>
<label for="category_ID">Tool Category: </label><br>
<input type="checkbox" name="category_ID[]" value="1" <?php echo $checked1; ?>> <label for="1">Automotive</label> <br>
<input type="checkbox" name="category_ID[]" value="2" <?php echo $checked2; ?>> <label for="2">Carpentry</label> <br>
<input type="checkbox" name="category_ID[]" value="3" <?php echo $checked3; ?>> <label for="3">Home Maintenance</label> <br>
<input type="checkbox" name="category_ID[]" value="4" <?php echo $checked4; ?>> <label for="4">Plumbing </label><br>
<input type="checkbox" name="category_ID[]" value="5" <?php echo $checked5; ?>> <label for="5">Yard and Garden</label> <br>
<input type="checkbox" name="category_ID[]" value="6" <?php echo $checked6; ?>> <label for="6">Hand Tools</label> <br>
<input type="submit" value="Edit Tool" >
<a class="block" href="<?php echo url_for('/members/delete_tool.php?id=' . $id); ?>">Delete Tool</a>
</fieldset>
</form>
<div class="push"></div>
</div>
<?php include(SHARED_PATH . '/footer.php'); ?>
You're looping over your results. This means with every loop you're setting one variable to "checked" and the rest to an empty string. So only the last one will be checked. The band-aid fix is to set unchecked as the default outside of the loop, and then change to checked only when it's needed.
But the real fix is to be pulling this info from the database and working with it instead of manually mapping database IDs to labels. By moving your condition into the join, you pull all the categories. The rows that have a tool ID are checked, and the others are not. You're also pulling the category names and IDs so you can programmatically build your checkboxes.
See here for DB sample: http://sqlfiddle.com/#!9/20b223/14/0
$tool = find_tool_by_id($id);
$tool["categories"] = [];
$sql = "SELECT c.category_name, c.category_ID, tc.tool_id
FROM category c
LEFT JOIN tool_category tc ON c.category_ID = tc.category_id
AND tc.tool_id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $_GET["id"]);
$result = $stmt->execute();
while($row = $stmt->fetch_assoc()) {
$id = $row["category_ID"];
$name = $row["category_name"];
$checked = $row["tool_id"] ? "checked" : "";
$tool["categories"][$id] = ["name" => $name, "checked" => $checked];
}
Now later on you can do this to automatically build all your checkbox inputs:
<?php foreach ($tool["categories"] as $id=>$category): ?>
<input type="checkbox" name="category_ID[]" id="category_<?=$id?>" value="<?=$id?>" <?=$category["checked"]?>>
<label for="category_<?=$id?>">
<?=htmlspecialchars($category["name"])?>
</label><br/>
<?php endforeach ?>

Foreach loop not printing first form

I am updating the code of my search page, for some reason if you search any users for example there are three users with the name "Peter" and if you search for them the first Peter prints only the inputs:
<input type="hidden" name="chatting_with" value="userexample"/><input type="hidden" name="chatting_logusr" value="userexample"/><input id="prponclick" class="openchatmsgdevices" type="submit" value="Enviar un mensaje" />
But the rest print correctly with the form:
<form target="u-n" method="POST" action="open_new_chat_with_user"><input type="hidden" name="chatting_with" value="userexample"/><input type="hidden" name="chatting_logusr" value="userexample"/><input id="prponclick" class="openchatmsgdevices" type="submit" value="Enviar un mensaje" /></form>
Heres the full code:
<?php
session_start();
include("../DD/ddd.php");
$logged_user = $_SESSION['valid_user'];
if(!$logged_user){return false;}
$query = "SELECT searched_for FROM searches WHERE `user` = '$logged_user' ORDER BY id_search DESC LIMIT 1";
$run_query = $all_conn->query($query);
$rows_searches = $all_conn->query($query)->fetch();
$searched_for = $rows_searches['searched_for'];
$no_allowed_spaces = preg_replace('/\s/', '', $searched_for);
$query_info = "SELECT * FROM user_info WHERE nombre LIKE '%".$searched_for."%' OR `user` LIKE '%".$searched_for."%'";
echo '<div class="n-ovf" style="overflow:auto;">';
if(strlen($searched_for) >= 1)
{echo '<div id="search-ico-con"><div id="s-ico-con"></div><div id="s-l-dvsr-con"><div id="s-l-dvsr"></div></div><div id="s-txt-con"><h3>'.$searched_for.'</h3></div></div><div id="s-dvsor"></div>'.
'<div id="search-hastag-con"><div id="s-hastag-con"><h1>#</h1></div><div id="shtag-l-dvsr-con"><div id="shtag-l-dvsr"></div></div><div id="shtag-txt-con"><h3>'.$no_allowed_spaces.'</h3></div></div><div id="shtag-dvsor"></div>';}
foreach($all_conn->query($query_info) as $got_users){
if(strlen($searched_for) == 0){echo '<div class="search-for-something"><h3>Buscar algo....</h3></div>'; return false;}
echo '<div class="searched-content-info">
<div style="float:left; width:100%; height:0.1px; position:relative; z-index:9586;" class="container-buttons-search-user">
<form target="u-n" method="POST" action="open_new_chat_with_user"><input type="hidden" name="chatting_with" value="'.$got_users['user'].'"/><input type="hidden" name="chatting_logusr"
value="'.$logged_user.'"/><input id="prponclick" class="openchatmsgdevices" type="submit" value="Enviar un mensaje" />
</form>
<input type="button" value="Visitar árbol"/>
</div>'.
'<div class="searched-photo"><img src="'.$got_users['foto'].'"></div>
<div class="searched-names"><h3>'.$got_users['nombre'].'</h3></div>
</div>
<div class="divisor-search-user"></div>';
}
echo '<div class="all-searched-content-divisor"></div>';
echo '</div>';
?>

PHP - Update all Fields at the same time AND delete image for each field independently

I am currently creating a basic CMS for practice purposes and I can't seem to figure out:
How to Update all fields at once AND delete (or upload new) images for each independent record
Any help would be appreciated :)
Updating All Fields Code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$sql = "UPDATE services SET page_title=:pageTitle, event_title=:eventTitle, event_content=:eventContent WHERE id=:id";
foreach ($id as $key => $value) {
$query = $connect->prepare($sql);
$query->bindValue(':pageTitle', $_POST['page_title'], PDO::PARAM_STR);
$query->bindValue(':eventTitle', $_POST['event_title'][$key], PDO::PARAM_STR);
$query->bindValue(':eventContent', $_POST['event_content'][$key], PDO::PARAM_STR);
$query->bindValue(':id', $id[$key], PDO::PARAM_STR);
if ($query->execute()) {
$message = 'Records updated.';
} else {
$message = "Failed to update records. Please contact Administrator.";
}
}
}
PHP/HTML Code:
<form method="post" action="">
<?php
$sql = "SELECT * FROM services";
$query = $connect->prepare($sql);
$query->execute();
$i = 1;
while($results = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<?php if ($i === 1) { ?>
<input type="text" value="<?php echo $results['page_title'] ?>" name="page_title">
<?php } ?>
<div class="service">
<input type="hidden" value="<?php echo $results['id'] ?>" name="id[]">
<input type="text" value="<?php echo $results['event_title'] ?>" name="event_title[]"/>
<?php
if ($results['event_imgSrc'] == '') { ?>
<img src='' style="width:100px; height:100px;">
<?php } else { ?>
<img src="<?php echo '../'.$results['event_imgSrc'] ?>" name="event_imgSrc">
<?php }
?>
<input type="file" name="image">
<input type="submit" name="del_img" value="Delete Image">
<input type="submit" name="upload_new" value="Upload New Image">
<textarea name="event_content[]"><?php echo $results['event_content'] ?></textarea>
</div>
<?php $i++; } ?>
<input type="submit" name="submit" value="Update"/>
<?php if (isset($message)) { ?>
<p><?php echo $message ?></p>
<?php } ?>
</form>

How to loop or foreach it

I cannot foreach loop my comment & reply system. I read many article and example but can't apply these in my case.
This is my comment system with reply, here every think is working well. But reply form work for only last/new comment. So i need to loop each comment. But can't do, please help me.
global $dbh;
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='$tutid' ORDER BY id DESC LIMIT 5") or die(mysqli_error($dbh));
echo'<div class="comments"><div id="updates"><div class="content"><comment>';
// Show only main comment
while($row = mysqli_fetch_array($results))
{ $id = $row['id'];
$qazi_id = $row['qazi_id'];
$username = $row['username'];
$description = $row['description'];
$parent_id = $row['parent_id'];
$date = $row['date'];
//echo comment
echo'<div class="comment">
<div class="cdomment_cheder">';
echo'<p>'.$username.' Says:</p>';
echo'<span>'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div></div></div>
<div class="cdomment_text">';
if ($description=="") {echo '';}
else echo''.htmlentities($description).'<br>';
echo '</div>';
//reply
echo'<div class="reply_box">Reply</div>';
//Reply form
echo'<div id="loader"></div><div class="reply_here" id="reply_here-'.$id.'" style="display:none;">
<form action="" method="post" id="repfrm" enctype="multipart/form-data">
<fieldset id="cmntfs">
<input type="hidden" name="username" tabindex="1" id="author" value="'.$username.'"/>
<textarea name="replycom" rows="2" tabindex="4" id="replycom" value=""></textarea>
<input type="hidden" name="parent_id" id="parent_id" value="0" />
<input type="hidden" name="tutid2" id="tutid" value="'.$tutid2.'" />
<button type="submit" name="submit" value="" tabindex="5" id="submit" class="repfrm">Post Reply</button>
</fieldset>
</form>
</div>';
// Show Reply of each comment
$query = "SELECT * FROM comments_reply WHERE parent_id ='".$id."'";
$res = mysqli_query($dbh,$query);
while($row = mysqli_fetch_array($res))
{ $id = $row['id'];
$qazi_id = $row['qazi_id'];
$username = $row['username'];
$description = $row['description'];
$parent_id = $row['parent_id'];
$date = $row['date'];
//echo reply
echo' <div class="rcontent"><replycomment><ul>
<div class="comment">
<div class="cdomment_cheder">';
echo'<p class="name">'.$username.' Says:</p>';
echo'<span>'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div></div></div>
<div class="cdomment_text">';
if ($description=="") {echo '';}
else echo''.htmlentities($description).'<br>';
echo '</div>';
echo'</ul><replycomment></div>';
} //reply while close
} //comment while close
echo'</div><comment></div>';

Update post from database

I'm trying to get my post to update just in case I make a mistake the first time around posting an article to my website.
Not sure what I'm doing wrong here.
Here is my update code:
<div class="row">
<?php
$post_title = "";
$description = "";
$id = $_GET['id'];
$result = mysql_query("SELECT title, description FROM htp_news WHERE id='$id'");
$post_title = mysql_result($result,0,"title");
$description = mysql_result($result,0,"description");
?>
<div class="row">
<form method="post" action="update-news.php">
<input type="hidden" name="ud_id" style="width: 100%" value="<? echo "$id"; ?>">
<div class="grid_12 botspacer60">
Title: <input type="text" name="ud_title" value="<?php echo "$post_title"; ?>">
<br /><br />
News Details:<br />
<textarea id="tiny_mce" name="ud_description" rows="8"><?php echo "$description"; ?></textarea>
</div>
<div class="grid_12">
<input type="submit" value="Update">
<input type="button" value="Cancel" onclick="window.location = '/admin'">
</div>
</form>
</div>
</div>
And here is my action page:
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/includes/database.php");
$ud_id = $_POST['ud_id'];
$ud_title = $_POST['ud_title'];
$ud_description = $_POST['ud_description'];
// Insert record into database by executing the following query:
$query="UPDATE htp_news SET title='$ud_title', description='$ud_description' "."WHERE id='$ud_id'";
mysql_query($query);
echo "The post has been updated.<br />
<a href='edit-delete-news.php'>Update another position.</a><br />";
mysql_close();
?>
I appreciate any guidance on the matter.
Add a space before of WHERE Clause in query.
Use below -
$query="UPDATE htp_news SET title='$ud_title', description='$ud_description' WHERE id='$ud_id'";
Try this you need quotes in query
$result = mysql_query("SELECT `title`, `description` FROM `htp_news` WHERE id='$id'");
$query="UPDATE htp_news SET `title`='".$ud_title."', `description`='".$ud_description."' "." WHERE `id`='".$ud_id."'";

Categories