deleting a comment you posted with php code? - php

I was wondering if you can maybe help me out here... I created a link sharing website and managed to create a comment on a shared link.
I want to give you a scenario of what I would like to achieve. Every comment made by user_1 for instance, can only be deleted by user_1 and admin.
I understand that when "deleting" it from the php page it must also be dropped from the database. How can you do this?
//I pressume where I INSERTED my post's 'vales' I must DELETE them again from there??
//It is very much alike from reply.php's code where you INSERT the data into the database. Now I just want to delete it.
//I don't know if this code below is correct??
$sql = "DELETE FROM
posts(post_content,
post_date,
post_topic,
post_by)
WHERE ('" . $_POST['reply-content'] . "',
NOW(),
" . mysql_real_escape_string($_GET['id']) . ",
" . $_SESSION['user_id'] . ")";
$result = mysql_query($sql);
if(!$result)
{
echo 'Your reply has not been saved, please try again later.';
}
else
{
echo 'Your comment has been deleted!';
}

Your Delete query has major syntax errors. You don't delete individual fields from a table - you CAN'T. you can only delete entire records. The proper syntax is:
DELETE FROM sometable WHERE (...)
Your where clause also has errors. You're not doing any comparison operations, just listing some values. Again, a syntax error. Most like you'd want this (guessing at your post's table primary key field name):
DELETE FROM posts WHERE (post_id = $id);

You should give your comments ID's, and simply perform delete from posts where ID = $id.
The SQL statement you currently have won't even execute. Look at the manual for how the syntax works.

What would really be helpful is some separation of presentation logic from db logic from bus. logic. Try a MVC pattern, which makes it a lot easier to parse through the code and to only look at DB or presentation or bus. logic code. Then, we could focus on the answer to the question posted.

Related

How do I write data into a mysqli database using a button

Hello Im writing a voting system for fun. The idea is that you vote on a music playlist, therefor the most popular song by vote gets played next. The track names as well as number of votes are stored in a mysql database. I am able to read data from my database and displaying the track names in a row with a button next to it. But I cant figure out how to make the button update the number of votes the track next to it has.
My database has a table called votecount with 3 columns called track_id track_name track_votes respectively. I havent included my update function below since it wont work at all and I suspect my fault lies with somewhere else.
I think of using the track id in a way of determining which track it should update by +1 each time the button next to it is pressed.
i have included connecting to the database in a separate file called connect.php
<?php
include 'connect.php';
$sql = <<<SQL
SELECT *
FROM `votecount`
SQL;
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo $row['track_name'] . " TotalVotes ( " . $row['track_votes'] . " ) <form action='test.php' method'post'>
<input name='" . $row['track_name'] . "' type='submit' id='" . $row['track_id'] . "'value='vote'></input>
<br/></form>";
}
?>
Any help will be greatly appreciated thanks in advance!
There are few ways to do it, the easiest would be a link, to your script where you pass in the track id a query string:
echo "vote";
Then inside of test.php retrieve the id $_GET['id'] then run the query to add a vote.
or you can use Ajax to perform a request to your script and pass in the track id.

Use an IF STATEMENT with INSERT IGNORE

I have a voting system, which users can use to vote on posts. Thing is, they can't vote twice on the same post. Which is good. I did that like this:
$query = "INSERT IGNORE INTO vote_id (vote, postid, userid)
VALUES ('1', '{$postid}', '{$userid}')";
$result = mysqli_query($db, $query);
header('Location: index.php');
(The $db is my variable that connects to the database.)
They can still click on the vote, even if it doesn't insert into the table. The problem is, when it is IGNORE they shouldn't be able to click.
How do I separate the INSERT and IGNORE, so I can use the IGNORE in an if statement? Or in any other way, that can change the layout of the page?
Without code showing "vote" it's hard to say, but if it's button, then you can simply query a SELECT for a user_id and post_id, and if it finds at least one row, then add disabled to button. Like that:
<button name="vote" value="1" disabled>Vote</button>
Or just don't display anything "to vote" at all when query returns rows.
Other way is to check session, but it'd let the same user to vote again after relogging.
Thing is, they can't vote twice on the same post. Which is good. I did that like this:
What you've shown us here doesn't prevent people from voting twice (a unique index on postid and userid will - but that's not in your post). I do hope you are cleaning those parameters before splicing them into a an SQL statement like that.
But that is a comment.
How do I separate the INSERT and IGNORE, so I can use the IGNORE in an if statement
While I'm not 100% certain, I would expect mysqli_affected_rows() to return 0 if no rows were inserted. A more robust solution would be to omit the 'IGNORE' from the SQL statement and handle the duplicate key error:
$result = mysqli_query($db, $query);
$error=mysqli_errno($db);
switch ($error) {
case 0:
// all good
header('Location: index.php');
break;
case 1062:
print "Please don't vote twice\n";
exit;
default:
trigger_error("Query failed " . $query . " // " . mysqli_error($db));
print "whoops";
exit;
}

multipage session storing in database

i'm trying to set up a simple multipage form, with the use of sessions to be later stored in a database in multiple tables.
however, i seem to have run into a problem. while the values of the last page get posted to the database, the session variables do not.
please, keep in mind.. me and my project partner are complete newbies to php/sql and might not have payed as much attention in class as we should have. most of the code is pretty much thrown together randomly. and identifying problems does not seem to be our strong suit.
first page / b_tickets.php
(simple html form with the values 'ticket_a', 'ticket_k' and 'ticket_vip')
second page / b_rooms.php
<?php
session_start();
$_SESSION['ticket_a'] = $_POST['ticket_a'];
$_SESSION['ticket_k'] = $_POST['ticket_k'];
$_SESSION['ticket_vip'] = $_POST['ticket_vip'];
?>
third page / b_ucp.php
<?php
session_start();
$_SESSION['room_s'] = $_POST['room_s'];
$_SESSION['room_s_extra'] = $_POST['room_s_extra'];
$_SESSION['room_d'] = $_POST['room_d'];
$_SESSION['room_d_extra'] = $_POST['room_d_extra'];
$_SESSION['room_3'] = $_POST['room_3'];
$_SESSION['room_3_extra'] = $_POST['room_3_extra'];
$_SESSION['room_10'] = $_POST['room_10'];
$_SESSION['room_10_extra'] = $_POST['room_10_extra'];
$_SESSION['pension'] = $_POST['pension'];
?>
which leads to
insert_ucp.php
(at this point an echo §_SESSION of the previous variables reveals that they are in fact still stored.)
<?php
session_start();
$con = mysql_connect("localhost","XX","XX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fatcity", $con);
$sql="INSERT INTO tickets (ticket_a, ticket_k, ticket_vip)
VALUES
('$_SESSION[ticket_a]','$_SESSION[ticket_k]','$_SESSION[ticket_vip]')";
$sql="INSERT INTO rooms (room_s, room_s_extra, room_d, room_d_extra, room_3, room_3_extra, room_10, room_10_extra, pension)
VALUES
('$_SESSION[room_s]','$_SESSION[room_s_extra]','$_SESSION[room_d]','$_SESSION[room_d_extra]','$_SESSION[room_3]','$_SESSION[room_3_extra]','$_SESSION[room_10]','$_SESSION[room_10_extra]','$_SESSION[pension]')";
$sql="INSERT INTO ucp (title, name, n_family, adress, a_housenumber, continent, country, province, region, city, telephone, email, password, payment, client, comment)
VALUES
('$_POST[title]','$_POST[name]','$_POST[n_family]','$_POST[adress]','$_POST[a_housenumber]','$_POST[continent]','$_POST[country]','$_POST[province]','$_POST[region]','$_POST[city]','$_POST[telephone]','$_POST[email]','$_POST[password]','$_POST[payment]','$_POST[client]','$_POST[comment]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
at this point the question is not in fact about how terrible we are when it comes to php/sql- thank you.. we already figured that out. with only pretty much three days to our deadline..
but why exactly the session variables aren't saved to the database. what exactly are we overlooking?
thank you very much in advance..
RUN query every time!!!
You create variable, then overwrite it 2 times than execute it
should be:
$sql = 'smth';
mysql_query($sql);
$sql = 'smth';
mysql_query($sql);
$sql = 'smth';
mysql_query($sql);
you have
$sql = 'smth';
$sql = 'smth';
$sql = 'smth';
mysql_query($sql);
And as I've said do not use mysql_*. And your code allows sql injection
First problem I see, is that $sql variable gets overriden 2 times in the last piece of code. So, only the last query gets executed.
Second, you should use this syntax to inject non-tribial vars into strings: "INSERT ... ${someArray[someKey]} ..." - note curly braces. This is not required here, but it will save you from troubles in the future.
Third, sanitize all the input data! You will have SQL injection in the last code example.
Last, no need to session_start() in each file - just place it once in bootstrapping file and require_once it.
I agree with E_p in that only one of your queries is ever going to be executed. doing what he suggested will allow all your queries to execute.
You may also want to take a look at your tables, just from looking at your query structure I see nothing wrong with them, but you may end up having a hard time getting the info you want back out. I could be wrong since you didn't post your table structures nor was your question really regarding this, but its just something I noticed and figured I would share. Your tables do not look like they are connected to each other by any foreign keys. This may not be needed for your project, but if you needed to pull all the form data related to all ticket_a entries then you would only get a list of sessionIDs corresponding to the ticket_a column, without any info from your 'rooms' or 'upc' tables. If that is what you are going for then its fine, otherwise you may want to look into it.

PHP/MySQL form not posting data to database

New to learning PHP form validation on same page. Please advise as to why my data might not be posting to the database. After filling out the form, it redirects to thank you page without sending data. Thanks!
http://pastebin.com/3T1W9Krx
Edit: Now that I know where my problem was, I have updated the Pastebin file to show the working code, which validates in the same page and checks the database for duplicate email addresses.
I was able to use Rick Kuipers suggestion below to find this error. I was trying to include a column for the primary key under VALUES, however I only needed the values for the INSERT keys, not ID or timestamp, as ID is set to auto-increment.
$sql = "INSERT INTO table (last_name, first_name, age)
VALUES (".
PrepSQL($last_name) . ", " .
PrepSQL($first_name) . ", " .
PrepSQL($age) . ")";
mysql_query($sql);
header("Location: volthankyou.php");
exit();
}
}
This could be because of a problem with your query.
Try doing the following:
echo mysql_error($db);
//header("Location: volthankyou.php");
This should display the error if there is any.
Check if mysql_query is true or false for your insert. Otherwise, it will ALWAYS try and then, redirect to thankyou. And as spencercw points out, mysql_select_db could also be failing. Always check the result of such methods.
P.S.: always check server logs

delete a row from my sql table

I'm still new to php and working my way around it but i'm stuck at the following piece:
code for deleting a row in my table
i have a link directing towards this piece of my script. i run through the first half just fine but when i press on submit and try to execute my delete query it won't go to my second if statement let alone get to the delete query.
$pgd is the page id
my hunch is there is problem with the action in the form i'm building after my while statement
forgive me for the wierd formatting of my msg but its 2am and very tired, i promise to format my questions in the future better! any help is appreciated
edit: ok other then the obvious mistake of missing method=post #.#;
edit:
hey everyone,
first of all, i'd like to thank everyone for their response.
i just started coding in php last weekend so forgive my messy codes. the code is still running locally and my main goal was to finish the functions and then work on securing my code.
now back to the issue, i'm sorry if i was vague about my problem. i'll try to reiterate it.
my issue isn´t selecting an item i want to delete, the issue is that it won´t get to the 2nd if statement.
Re-edit:
this time with my current code:
if($_GET['delete'] == "y")
{
//content hier verwijderen
$sqlcont1="SELECT * FROM content where id ='".$_GET['id']."'";
echo $sqlcont1;
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while($rowcont1= mysql_fetch_array($resultcont1)){
echo '<form class="niceforms" action="?pg='.$pgd.'&delete=y&remove=y&id='.$_GET['id'].'" method="post">';
echo '<h1>'.$rowcont1['Titel'].'</h1>';
echo '<p>'.$rowcont1['Content'].'</p>';
echo '<input type="submit" value="Delete article">';
echo '</form>';
}
if($_GET['remove']=="y"){
echo 'rararara';
$id=$_GET['id'];
$sqlrem="DELETE FROM content WHERE id="$id;
echo $sqlrem;
mysql_query($sqlrem);
}
}
echoing $sqlrem gives me the following now:
DELETE FROM content WHERE id=8
that being my current code, i get in to the second IF statement but now to get it to delete!
#everyone:
ok maybe thinking out loud or following my steps worked but the code works, i know its very messy and it needs fine tuning. i'd like to thank everyone for their help and feedback. i'm liking this and you'll probably see me alot more often with nubby questions and messy codes with no escapes :(
First of all, you have SQL injection vulnerability in your script. Anyone can add some string that will be attached to your query, possibly altering it in a way that can make almost anything with the data from your database.
Escape your values with one of anti-SQL-injection methods. Read more for example on php.net/manual/en/function.mysql-query.php
To the point...
Your deletion code will be executed only if you invoke URL with two params (remove and delete set to y. That means your URL should look similar to something.php?delete=y&remove=y. Maybe you just did not spot it.
Please give details about any errors that occured and tell me whether the above mentioned solution helped.
mysql_fetch_array() returns an array
your while statement acts as an if, and does not iterate thru the array returned as you think it does
you need something like
$all_rows = mysql_fetch_array($result);
foreach ($all_rows as $row) {
$sql = "delete from table where id = " . $row['id'];
}
It looks to me like you're mixing two forms together here: you're wanting to see if you went to the delete row form (the first few lines), and you're trying to present the delete row form (the while loop.) I would break these two things apart. Have a page that simply displays your forms for row deletes, and another page that processes those requests. And another page that brings you to the delete rows page.
For now, just echo all the values you're expecting to receive in $_GET[] and see if they are what you expect them to be.
You have a lot of problems in that script alone, so just to make things easier (considering you uploaded a pic), put an
echo $sqlrem;
in your second if statement, see if the query is displayed. If not, it means it doesn't even get to that part of code, if it gets displayed, copy it and run it in phpmyadmin. That should output a more coherent error message. Tell us what that is and we'll work it through.
I also noticed that your DELETE SQL query might have an issue. If your $pgd' id is a integer, you shouldn't include the ' single quote, that is for string only.
**Correction**
$sqlrem = "DELETE FROM content WHERE id = " . controw1['id'];
EDIT
Anyway, just to help out everyone, I typed out his code for easier viewing.
I think his error is $rowcont1['Tilel'] --> that might caused PHP to have an error because that column doesn't exist. I assumed, it should be `Title' causing an typo error.
if(_$GET['delete'] == "y") {
$sqlcont1 = "SELECT * FROM content where id ='" . $_GET['id'] . "'";
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while ($rowcont1 = mysql_fetch_array($resultcont1)) {
echo '<form class = "niceforms" action = "?pg=' .$pgd . '&delete=y&remove=y">';
echo '<h1>' . $rowcont1['Title'] . '<h1>'; // <-- error here
echo '<p>' . $rowcont1['Content'] . '</p>';
echo '<input type = "submit" value = "Delete article">';
echo '</form>';
}
if ($_GET['remove'] == "y"){
$sqlrem = "DELETE FROM content WHERE id = " . $rowcont1['id'];
mysql_query ($sqlrem);
}
}

Categories