I'm working with our project and I noticed that whenever I refresh my page the mysql query repeats itself. When I click a submit button It will go to same page and it will perform the query. Even though i used isset() method to the submitting button, still the query repeats when I refresh/reload the page. Thank you :) !
<html>
<body>
<head>
<link rel="stylesheet" type="text/css" href="Homepagestyle.css">
</head>
<form method = "POST" action = "Forum.php">
<?php
session_start();
mysql_connect("127.0.0.1", "root", "toor");
mysql_select_db("matutorials");
echo "Welcome " . "<a href = 'UserProf.php'>". $_SESSION['username'] . "</a> <br>";
if (isset($_POST['btnProg'])){
echo $_SESSION['prog'] . "<br>";
} else if (isset($_POST['btnNet'])){
echo $_SESSION['net'] . "<br>";
}
?>
<center><font face = 'verdana'><textarea cols = 70 rows = 6 name = 'txtpost'></textarea></font></center><br>
<center><input type = 'submit' name = 'btnPost'></center><br> <br>
<center><table>
<?php
if (isset($_POST['btnProg'])){
$_SESSION['pasamoto'] = 1;
$capRows = "SELECT * FROM page_post WHERE category_id = 1 ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer)){
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
?>
</table> </center>
<?php
session_start();
if(isset($_POST['btnPost'])){
$post_content = $_POST['txtpost'];
$dttime = date("Y-m-d") . " " . date("h:i:sa");
$var = $_SESSION['pasamoto'];
if ($var == 1){
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer)){
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
//}
if ($var == 2){
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer)){
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
//}
?>
</form>
</body>
</html>
If you refresh a page after submitting you form, the POST will still be recognised by some browsers and will cause a second POST to the code. You should update your code to trigger the SQL query on a separate page or function, and then redirect the user to the success / thanks page, where refreshing won't duplicate the query.
Alternatively, you can have a hidden field on your page which contains a unique token and compare it with a cookie. On page load, you save the token to a cookie and to the hidden field on the form. When you submit the form, validate that the token in the hidden form field matches the cookie, then delete the cookie. Refreshing the page after submission will cause the token validation to fail, preventing a duplicate SQL insert.
Just wash out the form data by redirecting the page after insert query
like header('location:home.php')
As #PeeHaa suggested in the comments above use Post-Redirect-Get concept.
Modified your code a bit. Try below:
Forum.php
<head>
<link rel="stylesheet" type="text/css" href="Homepagestyle.css">
</head>
<body>
<form method="POST" action="Forum.php">
<?php
session_start();
mysql_connect("127.0.0.1", "root", "toor");
mysql_select_db("matutorials");
echo "Welcome " . "<a href = 'UserProf.php'>". $_SESSION['username'] . "</a> <br>";
if (isset($_GET['show']))
{
echo $_SESSION['prog'] . "<br>";
}
else if (isset($_GET['show']))
{
echo $_SESSION['net'] . "<br>";
}
?>
<center><font face = 'verdana'><textarea cols = 70 rows = 6 name = 'txtpost'></textarea></font></center><br>
<center><input type = 'submit' name = 'btnPost'></center><br> <br>
<center><table>
<?php
if (isset($_GET['show']))
{
$_SESSION['pasamoto'] = 1;
$capRows = "SELECT * FROM page_post WHERE category_id = 1 ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer))
{
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
?>
</table> </center>
<?php
if(isset($_POST['btnPost']))
{
$post_content = $_POST['txtpost'];
$dttime = date("Y-m-d") . " " . date("h:i:sa");
$var = $_SESSION['pasamoto'];
if ($var == 1)
{
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer))
{
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
if ($var == 2)
{
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer))
{
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
}
header("Location:Forum.php?show=true"); // <==== Note this
?>
</form>
</body>
</html>
Explanation:
The above code will follow the Post-Redirect-Get pattern. The form will post the data to the same page and whatever task you want to perform after form post should be enclosed in,
if(isset($_POST['btnPost']))
{
...
}
and then redirect the user to the same page using,
header("Location:Forum.php?show=true");
the header function will redirect the user to the same page and the GET parameter show will decide what to show after the redirection. The content to show after redirection (or any other time) should be enclosed in,
if(isset($_GET['show']))
{
...
}
Related
I've got this script where users can see a table of projects. But only the admin can delete said projects.
$query = ("select * from projectlist");
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<tr>";
while( list($key, $value) = each($row)){
//Print value
echo "<td>" . $value . "</td>";
}
if($_SESSION['rights'] == 'administrator'){
echo "<td><i class='fa fa-times-circle-o'></i></td>";
}
echo "</tr>";
}
Every row has an id called projectid, which get called with the $query = ("select * from projectlist");.
You can see that if the admin is logged in, there will be an icon displayed. What I want it to do is that if the user clicks on the icon, the row will be deleted. I'm not really good with php, it took me a while only to get this script working.
If anyobody can help me with this, I'd appreciate it.
try this,
$query = ("select * from projectlist");
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<tr>";
while( list($key, $value) = each($row)){
//Print value
echo "<td>" . $value . "</td><td id='del".$value."'><button></button></td>";
}
if($_SESSION['rights'] == 'administrator'){
echo "<td><i class='fa fa-times-circle-o'></i></td>";
}
echo "</tr>";
Instead of mysql_fetch_array($result, MYSQL_ASSOC) you can use mysql_fetch_array($result)
$query = ("select * from projectlist");
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
$id = $result['id']; // you unique column in table
$col1 = $result['col1']; //similarly all other columns
echo "<td>$col1</td>";
if($_SESSION['rights'] == 'administrator'){
echo "<td><a href='your_current_page.php?id=$id'><i class='fa fa-times-circle-o'></i></a></td>";
}
echo "</tr>";
}
Code To Delete Row
if(isset($_GET['id']))
{
$id= $_GET['id'];
mysql_query("delete from table where id='$id'");
echo "deleted";//whatever you want to do
}
Ajax is not complicated at all.
I prefer jQuery when I need Ajax:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.11.0.js'></script>
<script type='text/javascript'>
$(function() { // when page loded
$(".del").on("click",function(e) { // clicking on a class=del thing
e.preventDefault(); // stop any submission from the button
$.post("delete.php",{ "id":$(this).val()},function(data) {
$("#somemessageDiv").html(data);
});
});
);
</script>
using class instead of ID since ID must be unique
echo "<td>" . $value . "</td>";
if($_SESSION['rights'] == 'administrator'){
echo "<td><button class='del' value='".value."'>DELETE</button></td>";
}
Now you need delete.php to take an id and return success or error
Create a form for delete particular row.
Create one hidden field with value will be id of that row.
Create one deleterow.php and write code for delete that row from database using delete query of mysql.
if($_SESSION['rights'] == 'administrator') {
<form type='post' action ='deleterow.php'>
<input type="hidden" name='rowid' value='<?php echo $rowid ;?>' />
echo "<td><input type='submit' name="submit" value="delete" /></td>";
</form>
}
I'm trying to get data from a database if a link is clicked.
I used the example codes suggested from this example -Getting mysql field data when a link is clicked?
But it doesn't work when I click on a link nothing comes up.
main.php
<?php
include('conn.php');
$sql2 = "SELECT Title FROM addpromo";
$result2 = mysql_query($sql2);
echo "<div id=\"links\">\n";
echo "<ul>\n";
while ($row2 = mysql_fetch_assoc($result2)) {
echo "<li> <a href=\"fullproject.php?title=\""
. urlencode($row2['Title']) . "\">"
. htmlentities($row2['Title']) . "</a>\n</li>";
}
echo "</ul>";
echo "</div>";
?>
This is displaying correct.but when I click at a link nothing is showing up in fullproject.php, Just a blank page.
fullproject.php
<?php
// Connect to server.
include('conn.php');
$projectname = isset($_GET['Title']);
$sql1 = "SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title'] . "<br />";
echo "<br /> ";
}
?>
Can someone help me to fix this, or any other way to make this(to get data from a database if a link is clicked) possible?
Change to this
main.php
<?php
include('conn.php');
$sql2="SELECT Title FROM addpromo";
$result2=mysql_query($sql2);
echo '<div id="links">';
echo '<ul>';
while($row2 = mysql_fetch_assoc($result2)){
echo '<li>'.htmlentities($row2['Title']).'</li>';
}
echo '</ul>';
echo '</div>';
?>
fullproject.php
<?php
if(isset($_GET['title'])){
include('conn.php');
$projectname= $_GET['title'];
$sql1="SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title']. "<br />";
echo "<br /> ";
}
}
?>
This is storing a boolean value $projectname= isset($_GET['Title']);, whether or not the title is set. Instead use $projectname = $_GET['Title'];
isset returns a boolean value (true/false) and you want the actual value of the variable:
$projectname= $_GET['title'];
Furthermore, you have to pass only the title as the URL parameter, without enclosing it within quotes. So there is an error in this line:
echo "<li> <a href=\"fullproject.php?title=" . urlencode($row2['Title']) . "\">"
Note the lack of \" after title=
i will use my old posted codes, coz i am working on the same program. what i want is how could i make it possible to save all selected values in one row which the studentid of a user will not be repeated. pls help...
<?php session_start(); ?>
<?php
//server info
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'user';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
echo 'Student ID: '. $voter.'';
echo "<br />";
if ($_POST['representatives']){
$check = $_POST['representatives'];
foreach ($check as $ch){
global $voter;
$mysqli->query("INSERT INTO sample (studentid, candidate1) VALUES ('".$voter."', '". $ch ."')");
echo $ch. "<br>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<script type="text/javascript">
<!--
function get_representatives_value()
{
for (var i=0; i < document.list.representatives.length; i++)
{
if (document.list.representatives[i].checked)
{
return document.getElementById('candidates').innerHTML = document.list.representatives[i].value
}
}
}
//-->
</script>
title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="candidate.css" rel="stylesheet" type="text/css">
</head>
<body> <p id="txt"></p>
<form name="list" action="president2.php" method="post" onSubmit="return get_representatives_value()">
<div id="form">
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM candidate_info WHERE position= 'representatives' AND department ='CCEITE' ORDER BY cand_id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>Student ID</th><th>Candidate ID</td><th>Course</th><th colspan = '3'>Name</th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->cand_studid . "</td>";
echo "<td>".$row->cand_id."</td>";
echo "<td>" . $row->course . "</td>";
echo "<td coslpan ='5'>" . $row->fname . " ". $row->mname ." ". $row->lname ." </td>";
echo "<td><input type ='checkbox' name='representatives[]' id='". $row->cand_studid ."' value='" . $row->cand_studid . "' onchange='get_representatives_value()' /></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
echo "<input type='submit' name='representatives value='Submit' />";
?>
</div>
</form>
<table>
<tr><td>Preview List</td></tr>
<tr><td>Candidates: </td><td id="candidates"> </td></tr>
</table>
</body>
</html>
this the preview of my output and selected checkbox
now this is the preview of my database. this one is the result of my selection from the above preview which the student ID is repeated on my table.
what i want is to save like this
and one more thing, how could i make a preview of all i selected on the checkboxes, here is my preview output, below the table is the preview list of candidates as the user click on the checkbox. but it returns only one and only the last selected value as selecting multiple checkboxes will be printed. how could i apply this method in an array coz this preview, i remove the '[]' on my input type name='representative' and it works, but not in the presence of '[]'.
I don't know if I read your questions correctly, but...
For your Insert Issue
I don't know if the way you're storing the data in the database is the best method, but if you want to use what you have, you can just insert your record like this (assuming you've put in some validation script to prevent users from selecting more than 2 candidates):
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
if ($_POST['representatives']){
$check = $_POST['representatives'];
$mysqli->query("INSERT INTO sample (studentid, candidate1, candidate2) VALUES ('". $voter ."', '". $check[0] ."', '". $check[1] ."')");
}
}
?>
For your Preivew Issue:
I'm assuming you wanted something like this for your preview to show the studentid with the choices for candidate1 and candidate2:
<h3>Preview List</h3>
<table>
<tr><th>StudentID</th><th>Candidate 1</th><th>Candidate 2</th></tr>
<?php
$result = $mysqli->query("SELECT * FROM candidate_info");
while ($row = $result->fetch_object())
{
echo "<tr><td>" . $row->studentid . "</td><td>" . $row->candidate1 . "</td><td>" . $row->candidate2 . "</td></tr>";
}
$mysqli->close();
?>
</table>
Here is some pseudo code you can use to update the sample table:
$candidate=array(null,null);
$candidateCounter=0;
foreach ($check as $ch){
$candidate[$candidateCounter]=$ch;
$candidateCounter++;
if(candidateCounter>1){
something wrong, only 2 candidates can be selected
}
}
UPDATE sample set $candidate1=candidate[0], $candidate2=candidate[1] WHERE
studentid=$voter
I have three php scripts. main.php questions.php and values.php
Here's the code
main.php
<html>
<head>
<title></title>
</head>
<body>
<h1>Be Prepare for the battle</h1>
<?php
$strTitle = "Begin";
$strLink = "<a href = 'question.php?ques_id=1'>" . $strTitle ."</a>";
echo $strLink;
?>
</body>
</html>
questions.php
<?php
require_once('../connect.php');
$quesSQL = mysql_query("SELECT * FROM `questions` WHERE `ques_id`=". $_GET["ques_id"]);
if(!mysql_num_rows($quesSQL) >= 1)
{
die('Complete.');
}
$next = $_GET["ques_id"];
while($row = mysql_fetch_array($quesSQL)) {
$id = $row['ques_id'];
$strTitle = $row['ques_title'];
echo "<li>" . $strTitle . "</li><br/>";
}
$optSQL = mysql_query("SELECT `options`,`values` FROM questions_options WHERE " . $id . "= ques_id");
echo "<form action=\"values.php\" method=\"POST\">";
while($row = mysql_fetch_array($optSQL) ) {
$strOptions = $row['options'];
$strValues = $row['values'];
echo "<input type =\"radio\" name =\"valueIn\" value=" . $strValues . " />" . $strOptions . "<br/>";
}
echo "</form>";
$strTitle = "<input type =\"submit\" value=\"Next\">";
$next = $next + 1;
$strLink = "<a href = 'values.php?ques_id=" . $next . "'>" . $strTitle ."</a>";
echo $strLink;
mysql_close();
?>
values.php
<?php
require_once('../connect.php');
$input = $_POST['valueIn'];
$ansSQL = mysql_query("SELECT `answer` FROM questions WHERE 1-".$_GET["ques_id"]."= ques_id");
$marks = 0;
if($input == $ansSQL)
{
$marks = $marks+1;
}
else
{
$marks = $marks+0;
}
echo $marks;
?>
Now problem is i have to pass one value from second script(questions.php) to third script(values.php).
And it is from the <form> section in radio button's name value "valueIn". But I can't do that. Because I'm sending another value ques_id with $strLink variable at the end of the second script.
So how can i do that?
I'm not sure why your using a link to handle what should probably be in the form. As stated by anusha you should be using a hidden input field for ques_id like so
questions.php
<?php
require_once('../connect.php');
$quesSQL = mysql_query("SELECT * FROM `questions` WHERE `ques_id`=". $_GET["ques_id"]);
if(!mysql_num_rows($quesSQL) >= 1)
{
die('Complete.');
}
$next = $_GET["ques_id"];
while($row = mysql_fetch_array($quesSQL)) {
$id = $row['ques_id'];
$strTitle = $row['ques_title'];
echo "<li>" . $strTitle . "</li><br/>";
}
$optSQL = mysql_query("SELECT `options`,`values` FROM questions_options WHERE " . $id . "= ques_id");
echo "<form action=\"values.php\" method=\"POST\">";
while($row = mysql_fetch_array($optSQL) ) {
$strOptions = $row['options'];
$strValues = $row['values'];
echo "<input type =\"radio\" name =\"valueIn\" value=" . $strValues . " />" . $strOptions . "<br/>";
}
$next = $next + 1;
$strLink = '<input type="hidden" name="ques_id" value="'.$next.'">';
echo $strLink;
$strTitle = "<input type =\"submit\" value=\"Next\">";
echo $strTitle;
echo "</form>";
mysql_close();
?>
Both variables when then be available via $_POST on the next step like below
$input = $_POST['valueIn'];
$ques_id = $_POST['ques_id'];
You can use hidden input like Mike's answer, or you can still use GET parameter like this:
questions.php
<?php
// .........
// .........
// .........
// .........
// add / change your code for this part
$next = (int) $next;
$optSQL = mysql_query("SELECT `options`,`values` FROM questions_options WHERE ques_id = " . $next);
echo '<form action="values.php?ques_id=' . ($next+1) . '" method="POST">';
while($row = mysql_fetch_array($optSQL) ) {
$strOptions = $row['options'];
$strValues = $row['values'];
echo '<input type="radio" name ="valueIn" value="' . $strValues . '" />' . $strOptions . '<br/>';
}
echo '<input type="submit" value="Next">';
echo "</form>";
mysql_close();
// end change
?>
values.php
<?php
// add / change your code for this part
$_GET["ques_id"] = (int) $_GET["ques_id"];
$ansSQL = mysql_query("SELECT `answer` FROM questions WHERE ques_id = " . ($_GET["ques_id"]-1));
// end change
// .........
// .........
// .........
// .........
You can add multiple parameters with 'a' tag.
Like
"<a href = 'values.php?ques_id=".$next." & ques_id1=1'>" . $strTitle ."</a>"
You can also use a hidden input field for variable $question_id and submit the form
i try to make checkboxes. When i click checkbox it makes isPremium = 1 if i click a checked checkbox it makes isPremium = 0
However: when i click a checked checkbox it does not work..
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
$dbResult = mysql_query("select * from profiles");
while ($info = mysql_fetch_array($dbResult)) {
if ($info['isPremium'] == 0)
echo "<input type=checkbox name='check2[]' id='check2' value=" . $info['id'] . ">";
else
echo "<input type=checkbox name='check1[]' id='check1' value=" . $info['id'] . " checked>";
echo $info['profileName'] . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
if (isset($_POST['check2'])) {
$arrPremium = $_POST['check2'];
foreach ($arrPremium as $result) {
mysql_query("UPDATE profiles set isPremium=1 where id=" . $result . "");
}
}
else
{
$arrPremium = $_POST['check1'];
foreach ($arrPremium as $result2) {
mysql_query("UPDATE profiles set isPremium=0 where id=" . $result2 . "");
}
}
}
?>
when i click a checked checkbox it makes another checkbox unclick.
This is the checkbox page
I have refactored your code into this:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$update = (isset($_POST['check']) && is_array($_POST['check']));
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
while ($info = mysql_fetch_array($dbResult))
{
if ($update)
{
$info['isPremium'] = (in_array($info['id'], $_POST['check']) ? 1 : 0);
mysql_query("UPDATE profiles SET isPremium = " . $info['isPremium'] . " WHERE id = " . $info['id']);
}
echo "<input type=checkbox name='check[]' value=" . $info['id'] . ($info['isPremium'] == 0 ? "" : "checked") . " />";
echo htmlspecialchars($info['profileName']) . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
?>
There were several problems with your original code:
Several HTML input elements with the same ID. This is wrong. We can have several elements with the same name attribute, but the id attribute should be unique for each element.
The database UPDATE code runs after displaying the form. This is wrong. In this case, we should update the database prior to generating the HTML output.
IMPORTANT: There is no need of two different POST arrays (check1 and check2). We only need one array. The checked boxes will be posted by the browser. The unchecked boxes will not be posted by the browser. As the id is the value, we can use the in_array function to verify if the checkbox for an item was checked or not.
It is a good idea to escape things you will output as HTML from the database. Otherwise, the application is vulnerable for some kinds of attack. The function htmlspecialchars is useful for this purpose.
If I understand correctly what you're trying to achieve, your code is needlessly complicated. You should use isset to check whether the value of a checkbox was included in the $_POST array. If yes, the checkbox was checked.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
echo "<form action='#' method='post'>";
$dbResult = mysql_query("SELECT * FROM profiles");
$profileid = array();
while ($info = mysql_fetch_array($dbResult)) {
echo "<input type=\"checkbox\" name=\"" . $info['id'] . "\" " . ($info['isPremium'] != 0 ? "checked " : "") . "/>";
echo $info['profileName'] . "<br />";
$profileid[] = $info['id'];
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
foreach ($profileid as $id) {
if (isset($_POST[$id])) {
mysql_query("UPDATE profiles SET isPremium=1 WHERE id=" . $id);
} else {
mysql_query("UPDATE profiles SET isPremium=0 WHERE id=" . $id);
}
}
}
?>
Checkboxes typically send the value "on" to the server, regardless of what value attribute is set. If you can, try to use radio buttons instead, as these send the proper value to the server. If that's not an option, have the name of the checkbox be check1[".$info['id']." and access array_keys($_POST['check1']).