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

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.

Related

Display single record based from the URL (id)

I have a website where it displays all of my records. I can click on an individual record and it gets the student_id of that record and updates it to the URL eg. view_student.php?id=12.
It then takes me to a new page where I want it to display all the information about that record, in this case, show all information about student number 12, but none else.
I haven't a clue how to carry out the statement to display all of the information for that record, this is what I have so far:
if (isset($_GET['student_id'])) {
echo $row['student_name'] . $row['student_age'] . $row['student_gender'];
}
This is a standalone page with nothing else on it. view_student.php simply uses a require function to this script. This code does not display anything, nor does it display any errors. I'm using PDO and I have made sure I'm connected to the database.
My guess is that I will need to use a WHERE clause but I'm just not too sure
Thank you
You can use below PDO query to fetch your data
$statement = $db_con->prepare("select * from student where student_id = :student_id");
$statement->execute(array(':student_id' => $_GET['student_id']));
$row = $statement->fetchAll(PDO::FETCH_ASSOC);

Updating certain columns in a mySql table?

Hello I am new into PHP and Mysql - well I am developing an android app that will retrieve some user data from a server mysql db table - data like username, firstname, last name, addresse etc..and the user has the option to edit that all or some of them...and lastly click the update button to update the data back to the mysql database.
So the problem is - should I return all the values (edited and those that are not) with the POST['username'], POST['fname'], .... etc - and then update the database with data that are changed and not changed - or should I RETURN ONLY THE EDITED DATA and then somehow update these fields in the table (BUT i am not sure how to implement this - to make a SWITCH statement with cases for every type of POST['fname'] and there update every single column with the POST value)
OR DO YOU KNOW SOME BETTER LOGIC/PATTERN FOR THIS - paste some links with examples/tuts if you know?
THANKS
This works in PHP, although prepared statements are better:
$sql = "
UPDATE userData
SET
";
if(isset($_POST['firstname'])
$sql .= "`firstname` = '" . $_POST['firstname'] . "'";
if(isset($_POST['lastname'])
$sql .= "`lastname` = '" . $_POST['lastname'] . "'";
// You get the picture
$sql .= "
WHERE userid = $id";
You should send a flag indicate the edited fields and depending on the flag write your update statement, for example if username and fname are changed, send a flag USERNAME_FNAME_CHANGED and then expected 2 fields username and fname being sent from your device. Then in the server implements a switch statement to write the update statement accordingly.

deleting a comment you posted with php code?

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.

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);
}
}

Display database contents? PHP / MySQL

So I have a chatroom type of database where the text that a user inserts gets stored into a databse as their username in one field and their message in the other. I want to have my page output the database info, so that people can see each others messages.
How do I do this?
Also, is it possible to make a for loop that checks to see if the database has been updated with a new message, therefore it reloads the page? (Then the page outputs the database info again to update everyones messages)
Please help.. i'm so confused.
Take a look at MySQL functions in PHP manual. You need to connect to the server/database and run a select query to get the data from tables.
As for the loop: you could use JavaScript setInterval function and combine that with AJAX call to periodically poll for new records.
Like the others have said, you will want to connect to your database and then query the table that you have the data in.
while($row = mysql_fetch_assoc($results))
{
echo $row['username'] . " said: " . $row['message'] . "<br />";
}
I use mysql_fetch_assoc() instead of mysql_fetch_array() since the arrays are associative arrays (not indexed by integers, but rather by names (associations))
As for displaying the update on the page dynamically, that involves AJAX. Basically what that means is that your page will call out to a background script to get the new records from the database. This would require a new field in your 'messages' table, something like 'msg_delivered' that you could set to '1' when it has been fetched.
You should check out this if you are interested in making an AJAX chat client: http://htmltimes.com/javascript-chat-client-in-jquery.php
To read anything from a mysql database you would use the mysql_connect() and the mysql_query() functions
eg:
$link = mysql_connect('localhost', 'root', '');
$results = mysql_query('select * from messages');
while($row = mysql_fetch_array($results))
{
echo $row['username'] . ': ' . $row['message'].'<br />';
}
To display new messages the best way would be to use AJAX and poll the database from there, either loading a separate page into a DIV or getting XML back and placing into HTML tags. I would recommend using JQuery for these kinds of tasks. Check http://www.sitepoint.com/article/ajax-jquery/ for an example.

Categories