How do I delete specified address row? - php

My add_id is a primary key. I have displayed all the addresses from the same cus_id but with different add_id. I want to delete a specified row of address but when I press the delete button, the page refresh but no data was deleted. Please look at my codes, thank you.
These are the codes involved, and my db:
<?php
$cus_id = $_SESSION['id'];
//To show all the addresses with the same cus_id
$result2 = mysqli_query($connect, "SELECT * FROM customer_address WHERE cus_id='$cus_id'");
?>
<?php
if (isset($_GET['del'])) {
$add_id = $_GET["id"];
mysqli_query($connect, "DELETE FROM customer_address WHERE add_id='$add_id'");
}
?>
<?php
while ($row1 = mysqli_fetch_assoc($result2)) {
?>
<div class="addrow">
<div class="add_box">
<p id="name_row"><?php echo $row1['name']; ?> </p>
<p id="phone_row"><?php echo $row1['contact']; ?> </p>
<p id="add_row"><?php echo $row1['address']; ?></p>
</div>
<div class="btn_box">
<input type="button" name="editbtn" class="editbtn" value="Edit">
<input type="button" name="deletebtn" class="deletebtn" value="Delete">
<input type="button" name="defaultbtn" class="defaultbtn" value="Set As Default">
</div>
</div>
<?php
}
?>
<?php
if (isset($_GET['del'])) {
$add_id = $_GET["id"];
mysqli_query($connect, "DELETE FROM customer_address WHERE add_id='$add_id'");
echo ("<script>location.href = 'cus_address.php?msg=$msg';</script>");
}
?>

Firstly, you need to change from '$cus_id' to '".$cus_id."' because $cus_id is parameter.
<?php
$cus_id = $_SESSION['id'];
//To show all the addresses with the same cus_id
$sql = "SELECT * FROM customer_address WHERE cus_id='".$cus_id."'";
$result2 = mysqli_query($connect, $sql);
?>
When delete data, you need to add both cust_id and add_id on query follow as below:
<?php
if (isset($_GET['del']))
{
$cust_id = $_GET["id"];
$add_id = $_GET["add_id"];
mysqli_query($conn, "DELETE FROM customer_address WHERE add_id='".$add_id."' and cus_id='".$cust_id."'");
}
?>
Next, check data exist before looping and add "&add_id="
<?php
if(mysqli_num_rows($result2) > 0)
{
while($row1 = mysqli_fetch_assoc($result2))
{
?>
<div class="addrow">
<div class="add_box">
<p id="name_row"><?php echo $row1["name"]; ?> </p>
<p id="phone_row"><?php echo $row1["contact"]; ?> </p>
<p id="add_row"><?php echo $row1["address"]; ?></p>
</div>
<div class="btn_box">
<input type="button" name="editbtn" class="editbtn" value="Edit">
<input type="button" name="deletebtn" class="deletebtn" value="Delete">
<input type="button" name="defaultbtn" class="defaultbtn" value="Set As Default">
</div>
</div>
<?php
}
}else{
//Display... when no data have been found
}
?>

Related

How to submit just one button from a set of buttons that are displayed using a php while-loop

I am coding a website for an online university portal where I have a programs/courses page in which I am displaying the programs/courses on the page using data from the database in a PHP while-loop I have the enroll buttons also being displayed in that same while loop. but I'm having a bit of difficulty submitting the enroll buttons as when I click one of them all of them get submitted.
can anyone please let me know what I'm doing wrong here or if I have to use any javascript in this case!
<?php
session_start();
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'htdatabase');
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$id = $_SESSION['userID'];
$sql = "SELECT * FROM programs";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$i = '';
$progID = $row["progID"];
$name = $row["progName"];
$halfTime = $row["halfTDuration"];
$fullTime = $row["fullTDuration"];
$fee = $row["fee"];
$descrip = $row["description"];
$stringname = strval($name);
$spaceRemoved = str_replace(' ', '', $stringname);
?>
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<?php echo "<button class='btn btn-link' type='button' data-toggle='collapse' data-target='#$spaceRemoved' aria-expanded='false' aria-controls='$spaceRemoved'> $name </button>"; ?>
</h5>
</div>
<?php echo "<div id='$spaceRemoved' class='collapse' aria-labelledby='headingOne' data-parent='#accordionExample'>"; ?>
<div>
<div class="ccard-body col-md-9">
<h6><?php echo $descrip; ?></h6>
<hr>
<h5>Duration:</h5>
<h6>Full time: <?php echo $fullTime; ?></h6>
<h6>Half time: <?php echo $halfTime; echo $i; ?></h6>
<hr>
<h5 style="display: inline-block;">Estimated fees: $</h5><h5 style="display: inline-block;"><?php echo $fee ?></h5>
</div>
<form action="programs.php" method="post">
<div id="enroll" class="col-md-3">
<?php
$sql1 = "SELECT * FROM userprograms WHERE userID = '$id' AND progID = '$progID'";
$result1 = $con->query($sql1);
if ($result1->num_rows > 0) {
echo '<div id="enrolled" name="enrolled">ENROLLED</div>';
} else {
if (isset($_POST["enroll"])) {
$enrollqry = "insert into userprograms (userID, progID) values ('$id' , '$progID')";
mysqli_query($con, $enrollqry);
}
echo "<button name='enroll'type='submit'>ENROLL</button>";
}
?>
</div>
</form>
</div>
</div>
<?php
}
} ?>
You can specify a value for the button. like
<button name='enroll' value="<?php echo $program_id?>" type='submit'>ENROLL</button>
Then when checking for $_POST['enroll'] check the value and also validate it before entry to db.
After clicking the submit button a browser will send a POST request to programs.php with a form data, that includes values of input & button tags.
<input type="submit" name="course1" value="42">Subscribe</input>
<input type="text" name="first_name" placeholder="Your name"/>
Will send
course1=42
first_name=...
So you should either give a unique name to each submit button to be able to distinguish them on the server-side, or set up distinct values, as #mohamed-jailam mentioned above.

How to display a post and its comments?

I want to view all posts, all comments for each post at once. While I have no problems with displaying posts, displaying comments is already a problem. One post can have multiple comments, so I have no idea how to create a query to display this. I tried to use LEFT JOIN but it didn't help. I include a table schema below the code to make my problem easier to understand.
<?php foreach ($tweet->userData as $user)
{ ?>
<div class='col-xl-8' id='posty'>
<div class='row' id='time'>
<div class='btn-block d-flex justify-content-between'>
<div class='imie'>
<?php echo $user['autor'] ?>
</div>
<div class='czas'>
<?php echo $user['date_to_add'] ?>
</div>
</div>
</div>
<?php echo $user['comment'] ?>
<form action='' method='post' id="myForm">
<div class='row'>
<div class='col-12 col-xl-12 d-flex justify-content-between' id='icon'>
<button class='button2' name='dodaj_like' style="background-color: <?php if($user['like_color']==1){echo '#00FA9A';}else{echo 'black';} ?>" ><i class='fas fa-heart' ></i><input type='hidden' name='like' value="<?php echo $user['id']?>" /><span id="font"><?php echo $user['likes']?></span></button>
<button class='button2' name='dodaj_dislike' style="background-color: <?php if($user['dislike_color']==1){echo '#00FA9A';}else{echo 'black';} ?>"><i class='fas fa-heart-broken'></i><input type='hidden' name='dislike' value="<?php echo $user['id']?>"/><span id="font"><?php echo $user['dislikes']?></span></button>
<button class='button2' name='dodaj_comment' id="com" ><i class='far fa-comment-dots'></i><input type='hidden' name='comment' value="<?php echo $user['id']?>"/><span id="font">Comment</span></button>
<button class='button2' name='dodaj_share' style="background-color: <?php if($user['share_color']==1){echo '#00FA9A';}else{echo 'black';} ?>" ><i class='far fa-share-square' ></i><input type='hidden' name='share' value="<?php echo $user['id']?>"/><span id="font"><?php echo $user['shares'] ?></span></button>
</div>
</div>
</form>
<div class="row d-flex">
<div class="col-xl-12 bg-success ">
<form method="post">
<textarea id="form103" class="md-textarea form-control" rows="5" placeholder="Co słychać?" name="komentarz"></textarea>
<div>
<?php echo $aabbcc ?? '' ?>
</div>
<div class="button">
<button class="btn btn-danger mt-2" name='dodaj_comment'><input type='hidden' name='com' value="<?php echo $user['id']?>"/>Publikuj</button>
</div>
</form>
</div>
</div>
</div>
<?php } ?>
$id = $_GET['id'];
$session = $_SESSION['id'];
$sql = $this->database->connect()->prepare("SELECT post.id, CONCAT(first_name,' ', last_name) AS author, post.comment, post.date_to_add, post_comment.comment, post_comment.date_to_add FROM user JOIN post ON user.id = post.user_id LEFT JOIN post_comment ON post.user_id=post_comment.post_id where post.user_id = :user_id order by post.id DESC");
$sql->bindParam(':user_id',$id, PDO::PARAM_INT);
$sql->bindParam(':id',$session, PDO::PARAM_INT);
$sql->execute();
if($sql->rowCount())
{
$this->userData = [];
while ($row = $sql->fetch())
{
$this->userData[] = $row;
}
}
}
You can get the Comment form database for specific Post using post_id by selecting Comment Table:
$query="select * form post_comment where post_id=". $post_id;
here is the PHP Implementation :
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql_post = "SELECT * FROM post";
$result = $conn->query($sql_post );
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br> post id: ". $row["id"]. " - <br> Post: ". $row["post"]<br>";
$comment_query=$conn->query("select * form post_comment where post_id=". $row["id"]);
if ($comment_query->num_rows > 0) {
// output data of each row
while($comment= $result->fetch_assoc()) {
echo " <p>Comment ".comment['comment']." </p>";
}
}
}
} else {
echo "0 results";
}
$conn->close();

select query inside in select query php mysql

<?php
$query = "select * from comments t1
inner join users t2 on t1.user_id = t2.UserId
where usercomplain_id='$id'";
$run =mysqli_query($mysqli,$query);
while($row=mysqli_fetch_array($run))
{
$commentid = $row['comment_id'];
$comment = $row['comment'];
$username = $row['UserName'];
$userid1 = $row['UserId'];
$date = $row['CDate'];
$ageDate = time_elapsed_string($date);
?>
<div class="jumbotron" style="border:3px solid #2FAB9B; background-color:#68C8C6;">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<?php echo $ageDate; ?>
</div>
</div>
<br>
<label>Comment by <?php echo $username; ?></span></label><br>
<h5><b>Reply on this post</b></h5>
<?php
$query = "select * from Reply";
$run = mysqli_query($mysqli,$query);
?>
<a class="reply" data-role="<?php echo $commentid; ?>">Reply</a>
<br>
<br>
<div style="width:63%; display:none;" class="replyForm" data-role="<?php echo $commentid; ?>">
<form method="post">
<textarea name="comment[<?php echo $commentid; ?>]" cols="100" rows="4"></textarea><br>
<br>
<input type="submit" name="reply" class="btn btn-primary" style="float:right" value="reply">
</form>
</div>
</div>
<script>
It is a simple comment system in which after each comment I want to display replies on that particular comment using select inside a select query is returning only first record is there is any method to display those reply
Your second query, which in inside the while loop, is over writing the result set of the first as both use the handle $run
This one
<?php
$query = "select * from Reply";
$run = mysqli_query($mysqli,$query);
?>
Not quite sure if you even use the result of this query actually
But if you do change $run to say... $run1 and at least it will not destroy $run while still inside the while loop that is using $run.

update multiple columns in mysql database using $_GET

I want to update 3 fields in a row in 3 columns but I don't know how to do it. I already searched google and searcedh here but couldn't find any solution for it. I want to change title, paragraph and category of a blog post using $_GET using this way:
<?php
$id = $_GET['id'];
?>
<div class="middle">
<div class="content" style="width:100%;">
<div class="context" style="width:100%">
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$txt = $_POST['txt'];
$query = ("UPDATE tbl_post SET title='$title' WHERE id=$id");
$query = ("UPDATE tbl_post SET txt='$txt' WHERE id=$id");
when I use only one of $_title or $_txt, it works. But I couldn't find a way to update both fields together and couldnt update category selection.
full code of update.php page :
<?php require_once("config.php"); ?>
<?php require_once("header.php"); ?>
<?php
$id = $_GET['id'];
?>
<div class="middle">
<div class="content" style="width:100%;">
<div class="context" style="width:100%">
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$txt = $_POST['txt'];
$query = ("UPDATE tbl_post SET title='$title' WHERE id=$id");
$query = ("UPDATE tbl_post SET txt='$txt' WHERE id=$id");
$query = ("UPDATE tbl_post SET cat='$cat' WHERE id=$id");
mysql_query($query,$con);
header("location:insert.php");
exit();
}
?>
<form action="" method="post">
<?php
$id = $_GET['id'];
$query = "SELECT * FROM `tbl_post` WHERE(id=$id)";
$res = mysql_query($query,$con);
while($rows = mysql_fetch_array($res,MYSQL_ASSOC)){
?>
<p>عنوان مطلب</p>
<input type="text" name="title" style="width:200px; border:1px solid #8C8C8C" value="<?php echo $rows['title'] ?>">
<p>محتوای پست</p>
<textarea name="txt" style="width:300px"><?php echo $rows['txt'] ?></textarea>
<div class="clear"></div>
<?php } ?>
<p>دسته بندی</p>
<select name="cat" style="width:200px">
<?php
$query = "SELECT * FROM `tbl_cat` ORDER BY `id` ASC";
$res = mysql_query($query,$con);
while($rows = mysql_fetch_array($res,MYSQL_ASSOC)){
?>
<option value="<?php echo $rows ['id'] ?>"><?php echo $rows ['name'] ?></option>
</li>
<?php } ?>
</select>
<input type="submit" name="submit" class="" value="ثبت در دیتابیس" style="width:200px; margin-top:15px;">
</form>
</div>
</div>
</div>
<?php require_once("footer.php"); ?>
and insert.php :
<?php require_once("config.php"); ?>
<?php require_once("header.php"); ?>
<div class="middle">
<div class="content" style="width:100%;">
<div class="context" style="width:100%">
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$cat = $_POST['cat'];
$txt = $_POST['txt'];
echo 'title = '.$title.'<br>'.'category ='.$cat.'<br>'.'txt = '.$txt;
$query = "INSERT INTO tbl_post(`title`,`txt`,`cat_id`) VALUES ('$title','$txt','$cat')";
mysql_query($query,$con);
header("location:insert.php");
exit();
}
?>
<form action="" method="post">
<p>عنوان مطلب</p>
<input type="text" name="title" style="width:200px; border:1px solid #8C8C8C;">
<p>دسته بندی</p>
<select name="cat" style="width:200px">
<?php
$query = "SELECT * FROM `tbl_cat` ORDER BY `id` ASC";
$res = mysql_query($query,$con);
while($rows = mysql_fetch_array($res,MYSQL_ASSOC)){
?>
<option value="<?php echo $rows ['id'] ?>"><?php echo $rows ['name'] ?></option>
</li>
<?php } ?>
</select>
<p>محتوای پست</p>
<textarea name="txt" style="width:300px"></textarea>
<div class="clear"></div>
<input type="submit" name="submit" class="" value="ثبت در دیتابیس" style="width:200px; margin-top:15px;">
</form>
</div>
</div>
</div>
<?php require_once("footer.php"); ?>
Combine all the fields into a single query:
$title = $_POST['title'];
$txt = $_POST['txt'];
$cat = $_POST['cat'];
$query = "UPDATE tbl_post SET title='$title', txt = '$txt', cat = '$cat' WHERE id = $id";
Also, you should switch to parametrized queries instead of substituting into the SQL; this means using PDO or mysqli. Otherwise you need to escape the input data. See
How can I prevent SQL injection in PHP?

How to get the ID when selected the particular item?

I have a page that display products and I would like to get the product ID when I click on the particular item and pass it to another page.
May I know how can I achieve this?
I always get the last PID, my code:
<head>
<title>Toy-All</title>
<!--Wilmos: Using external CSS File to format the page style and fonts.-->
<link href="StyleSheet2.css" rel="Stylesheet" type="text/css" />
</head>
<body>
<form method = "post" action "getpid.php">
<div class="stylediv2-Middle-Toy-all">
<div class="transbox-Toy-all">
<?php
//open connection to MySQL Server
$connection = mysql_connect('localhost','root', '')
or die ('Unable to connect to !');
// select database for use
mysql_select_db('we-toys') or die ('Unable to select database!');
$query = 'SELECT p.*, price.priceN FROM product p, pricing price WHERE p.pid = price.pid and p.PGroup = 1 and p.PType = 1';
$result = mysql_query($query)
or die ('Error in query: $query. ' . mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_array($result))
{
echo '<div style="float:left;margin-right: 10px; margin-left: 10px;"><img src="'.$row[5].'" width=200px height=200px; ?> </div>
<h3>'.$row[1].'</h3>
<h1><span style="color:red"> $ '.$row[7].' </span>
<input type="hidden" name="pid" value= '.$row[0].' >
<input id="AddtoCart-Btn" type="Submit" value= "Add to Cart" >
</h1>
';
}
}
else
{
echo "No rows found!";
}
mysql_free_result($result);
mysql_close($connection);
?>
</div>
</div>
</form>
</body>
</html>
If you retrieve your data from $_SESSION['PID'], then you will always get the last ID because you keep reassign new value to that session.
You can just achieve this with a link to the another PHP page. For example:
<a href='anotherPage.php?id=<?php echo $row[0]; ?>'>Add to Cart</a>
A more completed code as requested
<?php
$query = 'SELECT p.*, price.priceN FROM product p, pricing price
WHERE p.pid = price.pid and p.PGroup = 1 and p.PType = 1';
$result = mysql_query($query)
or die ('Error in query: $query. ' . mysql_error());
?>
<?php while ($row = mysql_fetch_array($result)) { ?>
<h3><?php echo $row[1]; ?></h3>
<a href='anotherPage.php?id=<?php echo $row[0]; ?>'>Add to Cart</a><br><br>
<?php } ?>
And for anotherPage.php code
<?php
echo "You are trying to add this product ID to cart: " . $_GET['id'];
?>
You can use this form that i also provide in this code.
$query = 'SELECT p.*, price.priceN FROM product p, pricing price WHERE p.pid = price.pid and p.PGroup = 1 and p.PType = 1';
$result = mysql_query($query)
or die ('Error in query: $query. ' . mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_array($result))
{
$pid = ($row[0]);
$_SESSION['PID'] = $pid;
echo '<div style="float:left;margin-right: 10px; margin-left: 10px;"><img src="'.$row[5].'" width=200px height=200px; ?> </div>
<h3>'.$row[1].'</h3>
<h1><span style="color:red"> $ '.$row[7].' </span>
<form method="post" action="cart.php">
<input type="hidden" name="pid" value= '.$row[0].' >
<input id="AddtoCart-Btn" type="Submit" value= "Add to Cart" >
</form>
$pid = '.$row[0].';
</h1>
';
}
}
Now you should make a new page such as cart.php
echo $_POST['pid'];
If I understand you correctly, the following should work:
<form method="post" action="anotherPage.php">
<input type="hidden" name="id" value="<?php echo "$row[0]"?>"/>
<input id="AddtoCart-Btn" type="Submit" value="<?php echo "$row[0]" ?>" />
</form>
So basically when you click the product button, the id will be accessible in anotherPage.php
EDIT:
I rewrote your code to improve readability:
<div style="float:left;margin-right: 10px; margin-left: 10px;"><img src=<?php echo $row[5]; ?> width=200px height=200px; ?> </div>
<h3><?php echo $row[1]; ?></h3>
<h1>
<span style="color:red"> $ <?php echo $row[7] ?></span>
<form method="post" action="cart.php">
<input type="hidden" name="pid" value=<?php $row[0]; ?> >
<input id="AddtoCart-Btn" type="Submit" value= "Add to Cart" >
</form>
<?php $pid = $row[0]; ?>
</h1>
Avoid echo-ing out large chunks of HTML where possible. Try it now, If it fails provide the error message.
The above does, what the simple test below achieves:
<?php
$id = 1;
if (isset($_POST['submit_btn'])){
echo $_POST['id'];
}
?>
<form method="post" action="#">
<input type="hidden" name="id" value= <?php echo $id; ?> >
<input type="submit" name="submit_btn" value="submit">
</form>

Categories