How do i make delete button work? - php

I am trying to make a delete button but it doesn't work.
$interogare = "SELECT * FROM comments JOIN users ON users.user_id = comments.user_id WHERE movie_id='$movie_id' ORDER BY date_posted DESC";
$result = mysqli_query($dbc, $interogare) or die(mysqli_error($dbc));
while($rand = mysqli_fetch_assoc($result))
{
echo 'Delete';
if(isset($_GET['com'])) {
$haidi = mysqli_real_escape_string($dbc,$_GET['com']);
$sql_del = "DELETE FROM comments WHERE comment_id = '$haidi'";
mysqli_query($dbc,$sql_del);
header('location: film.php?id='.$_GET['id'].'');
exit();
}
}
When i click the delete link it takes me to
film.php?com='.$rand['comment_id'].'
page but nothing happens,it should delete my comment and take me back to the page where the comment was.Can someone please help me figure this out ?

does this work?
<?php
$query = "
SELECT *
FROM comments
JOIN users ON users.user_id = comments.user_id
WHERE movie_id=" . $movie_id . "
ORDER BY date_posted DESC";
$result = mysqli_query($dbc, $query) or die(mysqli_error($dbc));
if (isset($_GET)) {
$getData = $_GET;
}
while ($rand = mysqli_fetch_assoc($result))
{
echo 'Delete';
if (isset($getData) && $getData['com']) {
$id = mysqli_real_escape_string($dbc, $getData['com']);
$query = "
DELETE FROM comments
WHERE comment_id=" . $id;
$result = mysqli_query($dbc, $query);
if($result)
{
header('location: film.php?id=' . $id . '');
}
exit();
}
}
i would rather grab the post once, and then make sure we are passing the same object around, so i set GET to a var. then, i didnt like the way the ids were being set in the query, because it wasnt as easy to see. then i got down to the way you were creating the header, and it looked like you were passing the id from some GET data, instead of the id you just extracted and set to a varibale, see above..., or was that your intention to use $_GET['id'] for that actually instead?
also, you might need to pass your data link in the mysqli_real_escape_string() method

Related

How to set result SQL distinct query to one or different variables?

I'm creating a mobile library app, and for one function of the app I am trying to receive the bookID for all books checked out by a certain user. I would like to be able to echo back the results from the query in a string format (preferably with spaces in between each separate book id) so I can deal with the data later on within the app.
Many of the answers I have found online have simply shown how to execute the query, but not how to use the data afterwards. Sorry if this is a simple question to answer, I am a huge novice.
<?php
require "conn.php";
$email = $_POST["email"];
$mysql_qry = "SELECT * FROM user_data WHERE email like '$email'";
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID LIKE $user_id ORDER BY bookID DESC";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$result2 = mysqli_query($conn, $mysqlqry2);
}
else
{
echo "Error, user name not found";
}
$conn->close;
?>
You could append your results into an array and display values using implode():
<?php
require "conn.php";
$email = $_POST["email"]; // You may test here : if (isset($_POST['email']))
$mysql_qry = "SELECT * FROM user_data WHERE email = '$email'";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID = $user_id ORDER BY bookID DESC";
$result2 = mysqli_query($conn, $mysql_qry2);
if(mysqli_num_rows($result2) > 0)
{
$ids = [];
while ($row = mysqli_fetch_assoc($result2)) {
$ids[] = $row['bookID'] ;
}
echo implode(" ", $ids) ; // print list of ID
}
else
{
echo "No books checked out!";
}
}
else
{
echo "Error, user name not found";
}
$conn->close;
NB: I used your code here, but, you should have to look to parameterized queries to prevent SQL injections.
Your query $mysql_qry2 should be defined after to get $user_id.
Your LIKE $user_id could be replaced by =.
First thing first, always sanitize your data:
$email = filter_var( $_POST['email'], FILTER_SANITIZE_EMAIL );
$user_id = preg_replace( "#[0-9]#", '', $row['user_id'] );
Use
DISTINCT bookID instead of DISTINCT(bookID)
From your query: $mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY bookID DESC";
If you're not getting any result or the returned result is empty but the user_id does exist, then I think the query format is wrong.
What you should do instead
Change the ORDER BY: The query may be correct but mysql returned an empty result because the result order does not match.
Try this
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY userID DESC";
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY `primary_key_here` DESC";
Replace <strong>`primary_key_here`</strong> with the primary key name.
Run the query without conditionals and inspect the result
$query = mysqli_query( $conn, "SELECT bookID FROM books_checked_out DESC" );
var_dump( $query );
Use the result to inspect the rest of the query.
Rather than using your own protocol/format use something like JSON or xml in your response to the request.
This will give you better maintainability in the long run and allow you to easily handle the response in the browser with javascript, and most browsers will give you a nice display of JSON objects in the dev console.
You'll have to extract the user id from the result of the first query or you could do a joined query instead.
$email = validate($POST['email']); //where validate() will try to prevent sql injection
//joined query
$query =
" SELECT bookID FROM user_data
INNER JOIN books_checked_out on user_data.user_id = books_checked_out.userID
WHERE user_data.email='$email'
";
//not sure whether that should be user_id or userID looks like you have mixed conventions
//books_checked_out.userID vs user_data.user_id ... check your database column names
//loop through results
// may be empty if user email doesn't exist or has nothing checked out
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$response[] = ['bookID'=>$row['bookID']];
}
echo json_encode($response);
When receiving the result in php you can use json_decode() or in javascript/ajax it will automatically be available in your result variable.
if things aren't working as expected it can be a good idea to echo the actual sql. In this case
echo 'SQL IS: '.$query;
and test it against your database directly (phpmyadmin/MySQL-Workbench) to see if you get any results or errors.

deleting records from mysql table

Continuing with my simple CRUD, I'm stuck again...
So I have a table created called "usuaris" and a column called "id" which is my auto-increment and then another column called "usuari_nom". Now, I want to add "delete function", so when I am displaying the records of my table I've added a to delete it:
<div id="main">
<?php
global $conn;
$query = "SELECT * FROM usuaris";
if($grup_usuaris = mysqli_query($conn, $query)) {
echo "<table>";
echo "<tr><th>Usuaris</th><th>Accions</th></tr>";
while($row = mysqli_fetch_assoc($grup_usuaris)) {
echo "<tr><td>" . $row['usuari_nom'] . "</td><td>Eliminar usuari</td></tr>";
}
echo "</table>";
echo "+ Afegeix Usuari";
mysqli_free_result($grup_usuaris);
} else {
echo "query failed";
echo("Error description: " . mysqli_error($conn));
}
?>
</div>
So now, If I click on "eliminar usuari" it goes to the file where I am adding the query to delete, plus the id of that user; for example: "http://localhost/calendario/elimina_usuari.php?subject=6". But then, in the file elimina_usuari.php, how do I select the id to know what record to delete?
I've thought with $_GET but it doesn't seems to work, either with $_POST:
elimina_usuari.php
<?php
global $conn;
$usuari_id = $_GET['id'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
Any clue how can I get its id? Should I take it from the url somehow?
Thanks
you're doing fine.
just need to change this
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
as you're setting subject instead of id in your url
http://localhost/calendario/elimina_usuari.php?subject=6
^
and if you want to process id, like $_GET['id'], you need to change URL.
"http://localhost/calendario/elimina_usuari.php?id=6"
^ change here
EDIT
as per your comment,
you can use any $variable to $_POST or $_GET, it has nothing to do with the database column name.
Like you can use following.
"http://localhost/calendario/elimina_usuari.php?eve_mf=6"
and on elimina_usuari.php page,
$id = $_GET['eve_mf'];
and second part, why can I do that and I don't need to call it id as it is called in my db table?
Again, it's not the issue what you call variables in you local environment, all you to do(and should take care of) is to put right parameters in your sql query.
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
Here id is the name of your column name in your database. You can't change it here if you even want it to.
however, $usuari_id is your local variable, and you can change it whatever you want.
Hope I've explained what you're looking for :)
You can get the id with $_GET['subject'].
Please be aware about SQL injection as you are wrongly get the id of the user to be deleted:
$usuari_id = mysqli_real_escape_string($conn, $_GET['subject']);
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
You just need to Get the exact variable name or parameter name which you have sent with your url
I mean see your url contains subject=6
that means you have to get subject instead of id;
please replace this code
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
try this in elimina_usurai.php
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>

how correctly get country and other info from sql for specific id

I am trying to get country and other info from sql for specific id, only "id" displays correctly in both cases.
<?php
$sql = "SELECT * FROM `list` ORDER BY category ASC";
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
$id = $_GET['id'];
$country = $_GET['country'];
echo $id;
echo $country;
?>
and
<?php
$sql = "SELECT * FROM `list` ORDER BY category ASC";
$result = mysql_query($sql);
$id = $_GET['id'];
$country = $_GET['country'];
if (mysql_num_rows($result) > 0) {
while($rows = mysql_fetch_assoc($result)) {
echo $id;
echo $country;
}
}
?>
I think you have a column named id and another named country from which you want to collect the data in the country row of a certain record.
I have similar ideas to some of the comments and would like to highlight my thoughts in this answer.
$_GET superglobal is used to extract data form a URL parameter. If it is used to get the data from the record, you might want to use mysql_fetch_assoc($result)["country"]. For more information, please take a look at https://www.php.net/manual/en/function.mysql-fetch-assoc.php
and https://www.w3schools.com/php/php_superglobals_get.asp
To filter certain records according to some input id, you would want to use the WHERE clause. Link for more information:- https://www.w3schools.com/sql/sql_where.asp
The possible code might be:-
<?php
$id = $_GET["id"]
$sql = "SELECT * FROM `list` WHERE id='$id' ORDER BY category ASC";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
while($rows = mysql_fetch_assoc($result)) {
echo $rows['id'];
echo $rows['country'];
}
}
?>
PS: I have tried my best to answer the asked question provided the less information given. Hope it helps

obtaining comments for each post

hi I have to create a system of comments within various trhead I performed before and all the while the trhead 'while inside the comment and it works but is really slow and with a large number of threads often gives me timeout error how can I fix the problem?
function commenti($id) {
$query2 = "SELECT * FROM table2 WHERE numid='$id' ORDER BY id ASC";
$result2 = mysqli_query($conn,$query2);
if($result2->num_rows >0)
{
while($row2 = $result2->fetch_array(MYSQLI_ASSOC))
{
$idt2 = $row2['id'];
$testot2 = $row2['testo'];
return $testot2;
}
} else {
echo "No comment";
}
}
$query = "SELECT * FROM table1 where visualizza='1' ORDER BY id DESC";
$result = mysqli_query($conn,$query);
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$id = $row['id'];
$titolo = $row['titolo'];
$testo = commenti($id);
echo "$titolo $testo <br>";
}
}
mysqli_close($conn);
?>
I thought to use the join but if there are more duplicates also post comments
$query = "SELECT * FROM table1 left JOIN table2 ON table1.id = table2.numid where visualizza='1' ORDER BY id DESC";
I'm going to assume that you are trying to pull a ton of records. The best way to approach this is to add pagination and only load ~10-20 comments per page. depending on your server
Update:
#OP Basically on first load of the page you load ~10 comments, once they click view more then you load in the next few using ajax. Rinse and repeat.

MySQL query is running but not running

Alright let me explain myself here:
I am making an online text based game. I have a page where 3 things can happen:
They can create a position
Can edit a position
Can delete a position
So far I have creating a position working. I moved on deleting a position next. All was good and I got no errors, no warnings, etc.. And when I ran it, it came back to the screen it was supposed to after the script to delete the position ran. It is only supposed to come here after the query runs.
Well nothing happened and after 3 hours of trying crap I'm coming to you guys b/c I'm on my last leg. I still have no critical errors, nothing is making it fail: Here is my code.
<?php
//In the include file is the connection to the db
include("library/new_library.php");
//Below is the session id, gets their position id from the DB, than grabs whether or not they can edit the company
$user_id = $_SESSION['user_id'];
$sql = "SELECT ID, PositionID FROM users WHERE ID = '$user_id'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
$position = $row['PositionID'];
}
$sql = "SELECT * FROM tblCPositions WHERE PositionID = '$position'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
$editCompany = $row['Edit_Company'];
}
//Next I check for position edit and if they try to put in the position id of a position the company does not control it gives them a "nice" message.
$company = $_SESSION['company'];
if($_GET['pidedit']){
$position = $_GET['pidedit'];
$sql = "SELECT * FROM tblCPositions WHERE PositionID = '$position'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
if($row['CompanyID'] != $company)
{
$warning = "<div class='warning'>You are trying to edit a position that does not belong to your company. DO NOT TRY TO CHEAT THE SYSTEM!</div>";
}
else
{
$positionArray[] = array(ID => $row['PositionID'], name => $row['Name'], hire => $row['Hire'], fire => $row['Fire'], bid => $row['Contract'], edit => $row['Edit_Company'], finances => $row['Finances']);
}
}
}
//Here I check for $_GET delete
elseif($_GET['piddelete'])
{
$position = $_GET['piddelete'];
$sql = "SELECT * FROM tblCPositions WHERE PositionID = '$position'";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))
{
if($row['CompanyID'] != $company)
{
$warning = "<div class='warning'>You are trying to delete a position that does not belong to your company. DO NOT TRY TO CHEAT THE SYSTEM!</div>";
}
}
}
else
{
$sql = "SELECT * FROM tblCPositions WHERE CompanyID = '$company'";
$query = mysql_query($sql);
$number = mysql_num_rows($query);
$numberLeft = 12 - $number;
while($row = mysql_fetch_assoc($query))
{
$positionArray[] = array(ID => $row['PositionID'], name => $row['Name'], hire => $row['Hire'], fire => $row['Fire'], bid => $row['Contract'], edit => $row['Edit_Company'], finances => $row['Finances']);
}
}
//
if($_POST['submitNewPosition'])
{
$name = $_POST['positionName'];
$hire = $_POST['hire'];
$fire = $_POST['fire'];
$bid = $_POST['bid'];
$edit = $_POST['edit'];
$finances = $_POST['finances'];
$cid = $_SESSION['company'];
$sql = "INSERT INTO tblCPositions(CompanyID, Name, Hire, Fire, Contract, Edit_Company, Finances) VALUES ('$cid','$name','$hire','$fire','$bid','$edit','$finances')";
$query = mysql_query($sql);
if($query)
{
header("location: view_company.php?newp=success");
}
}
//Haven't finished this section yet
if($_POST['submitEditPosition'])
{
$name = $_POST['positionName'];
$fire = $_POST['hire'];
$fire = $_POST['fire'];
$bid = $_POST['bid'];
$edit = $_POST['edit'];
$finances = $_POST['finances'];
}
//This this is my problem area, this is where it says its running the query but its not.
if(isset($_POST['deletePosition']))
{
$deleteID = $_GET['piddelete'];
$deleteSql = "DELETE FROM tblCPositions WHERE PositionID = '$deleteID'";
$deleteQuery = mysql_query($deleteSql);
if($deleteQuery)
{
header("location: view_company.php?delete=success");
}
if(!$deleteQuery)
{
header("location: view_company.php?delete=failure");
}
}
UPDATE -
Ok so I got it working the problem was something I forgot, this form was just meant to be a "yes or no form" so I was doing post only to post the submit button, nothing else was on the form. What I had forgot was on the action="file.php" (what I had) I had forgotten to pass on the get variable so once I changed it to action="file.php?piddelete=12" it worked.
Thanks for everyones help I really appreciate it.
10 to 1 your variable $_GET['piddelete']; is empty. What do you get when you do this:
var_dump($_GET['piddelete']);
Disable the header redirect so that you can see the output.
edit
Or, as Nick pointed out, you can add die() statements to your queries:
$deleteQuery = mysql_query($deleteSql) or die(mysql_error());
If your query still runs, and the script doesn't die, and the position is still not deleted, you should check the query, it may be deleting 0 rows successfully. try killing at die($deleteSql); and run the query through MySQL's console.
/edit
Also, I'm compelled to introduce you to my good friend SQL injection attack. You should filter all data contained in the $_POST and $_GET superglobals before handing them over to the MySQL server. use mysql_real_escape_string().
Try to grok this:
whatever.com/your_url.php?pidedit=x'%3B%20DROP%20TABLE%20tblCPositions%3B%20--
If I were to execute that query string on your application, your tblCPositions table would be dropped.

Categories