Problems updating correct row in databse with php - php

I'm trying to create a voting system for artists played on my radio station. I'm using the source code from: http://dl.howcode.org/download/97ff383c7d4dc9939c65c9e6fab2a5dc
The problem I have found is that the votes update using the number from the first row in the database no matter which option is selected, thus if for instance the first row has 3 votes in and the user tries to vote on someone with 0 votes, it will change the votes for the correct artist to 4 instead of 1... I hope that makes sense?
The code I have is:
[EDIT] I have changed the queries to fetch assoc to make it easier to understand.
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}else{
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>
I could be missing something obvious, in my mind I'm thinking that I somehow need to iterate through the rows before setting the new value, if so, how and where?

It looks like you are always looping over all rows and updating the relevant row with the first value found. Adding a check on the ID should do:
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}elseif ($voteOption === $artist) { // Don't run UPDATE when we're on the wrong row.
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>

Related

prevent insert same id if the user/student not put timeout

i have two button on my homepage one is time-in and the other is time-out,
i want to prevent the user/student to time-in using same id if he did not put time-out on his last time-in to create valid entry. Hope you can help me.
here is my php code:
<?php
include_once('connection.php');
if(isset($_POST['submit0'])){
$rfid = $_POST['rfid'];
$time=date("H:i:s");
$sql = mysqli_query($conn, "SELECT * FROM stud WHERE rfid_num = '$rfid'");
$count = mysqli_num_rows($sql);
if ($count == 0 ) {
header("location:notexist.php");
} elseif (empty($row['timeout'])) {
header("location:page say the user/student need to put timeout first before time-in again");
} else {
while( $row = mysqli_fetch_array($sql)) {
$rfid=$row['rfid_num'];
$id=$row['id'];
$name0 = $row['name'];
$course0 = $row['course'];
$image = $row['image'];
$InsertSql = "INSERT INTO student_att(rfid_num,id,name,course,image,timein) VALUES ('$rfid','$id','$name0','$course0','$image','$time')";
$res = mysqli_query($conn, $InsertSql);
}
}
}
?>
this is my answer just wanna share it, i just add select student_att table
to fetch the data and check if timeout column is empty.
<?php
include_once('connection.php');
if(isset($_POST['submit0'])){
$rfid = $_POST['rfid'];
$time=date("H:i:s");
$sql = mysqli_query($conn,"select * from stud where rfid_num ='$rfid' ");
$count = mysqli_num_rows($sql);
if ($count == 0) {
header("location:notexist.php");
}else{
while( $row = mysqli_fetch_array($sql)) {
$rfid=$row['rfid_num'];
$id=$row['id'];
$name0 = $row['name'];
$course0 = $row['course'];
$image = $row['image'];
$sql1 = mysqli_query($conn,"select * from student_att where rfid_num ='$rfid' order by number DESC limit 1 ");
while( $row = mysqli_fetch_array($sql1)) {
if(empty($row['timeout'])){
header("location:logout.php");
}else{
$InsertSql = "INSERT INTO student_att(rfid_num,id,name,course,image,timein) VALUES ('$rfid','$id','$name0','$course0','$image','$time')";
$res = mysqli_query($conn, $InsertSql);
}
}
}
}
}
?>

how to get /?pollid=test inserted into my url with having to type it into the url everytime.... new to php

I am really struggling with how I get /?pollid=test inserted into my url when the page loads. Right now I have to type it and then the feature will work. /?pollid=test is calling the column and values from my sql table. can i hard code it in?
<?php
$pollid = $_GET['pollid'];
$connect = mysqli_connect('localhost','root','','poll');
$query = "SELECT * FROM polls WHERE pollid = '$pollid'";
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($q)){
$id = $row[0];
$title = $row[1];
$pollid = $row[2];
$ipaddress = $row[3];
echo "<h1>$title</h1>";
?>
<table>
<form action="" method="POST">
<?php
$questions = "SELECT * FROM questions WHERE pollid = '$pollid'";
$q2 = mysqli_query($connect, $questions);
while($r = mysqli_fetch_array($q2)){
$question = $r[1];
$votes = $r[2];
$newvotes = $votes +1;
$ip = $_SERVER['REMOTE_ADDR'];
$newipaddress = $ipaddress."$ip,";
if (isset($_POST['vote'])) {
$polloption = $_POST['polloption'];
if ($polloption == "") {
die("You did select an option.");
} else {
$ipaddresse = explode(",", $ipaddress);
if (in_array($ip, $ipaddresse)) {
die("You have already Voted");
}else{
mysqli_query($connect, "UPDATE questions SET
votes='$newvotes' WHERE pollid='$pollid' AND question='$polloption'");
//store ip address of the user so can only vote once
mysqli_query($connect, "UPDATE polls SET
ipaddress='$newipaddress' WHERE pollid ='$pollid'");
die("You votes successfully!");
}
}
}
echo '<tr><td>'.$question.'</td><td><input type="radio"
name="polloption" value="'.$question.'" />'.$votes.'votes</td></tr>';
}
}
?>
<tr><td><input type="submit" name="vote" value="Vote"/></td></tr>
</from>
</table>
<div> </div>

if Checkbox is checked then update calibrated = 'yes' and if Checkbox is not checked then update calibrated = 'no'

Hi Can you help me i have check box name='calibrate', now i want this if Checkbox is checked then update calibrated = 'yes' and if Checkbox is not checked then update calibrated = 'no'.
because the problem here is even i have 'Update machine_and_equipments set calibtrated = '$yah' where id = '$id' it cannot update in database.
<?php
$res = mysql_query("select * from machine_and_equipments where id = '$id'");
$row = mysql_fetch_array($res);
$cal = $row['21'];
$d1 = $row['6'];
if($cal == "yes"){
$checkthis = "<td >Need to Calibrate?: <input type='checkbox' name='calibrate' onclick='OnChangeCheckbox(this), enable_text(this.checked)' id='myCheckbox' checked/><label id='val'><?php echo $yah; ?></label> ";
}
if($cal == "no"){
$checkthis = "<td >Need to Calibrate?: <input type='checkbox' name='calibrate' onclick='OnChangeCheckbox(this), enable_text(this.checked)' id='myCheckbox' /> ";
}
if((isset($_POST['calibrate']))== "yes"){
$yah = "yes";
$id = $_POST['id'];
$sql = "update machine_and_equipments set calibtrated = '$yah' where id = '$id'";
$res = mysql_query($sql) or die("could not be update". mysq_error());
}
if((isset($_POST['calibrate']))== "no"){
$yah = "no";
$id = $_POST['id'];
$sql = "update machine_and_equipments set calibtrated = '$yah' where id = '$id'";
$res = mysql_query($sql) or die("could not be update". mysq_error());
}
?>
Thanks in advance.
Try this code. I am not able to comment so i am writing this on answer. If it wont work let me know.
if(isset($_POST['id'])) {
if((isset($_POST['calibrate']))){
$yah = "yes";
} else {
$yah = "no";
}
$id = $_POST['id'];
$sql = "update machine_and_equipments set calibtrated = '$yah' where id = '$id'";
$res = mysql_query($sql) or die("could not be update". mysq_error());
}

Error on How to SUM up all the rows of a column by Query and PHP.

Here I am trying to add all the columns up from one table echo out the result.
I have a table with Points that have been recorded by user, every points gets added I would like to add it up and print it out as result for the users score.
I am getting an error where the SUM Query is run. and the result is 0.
Here is the PHP:
<?php
// see if the form has been completed
include_once("php_includes/check_login_status.php");
//include_once("php_includes/db_conx.php");
// Initialize any variables that the page might echo
$username = "";
$weight = "";
$weighthist = "";
$id = "";
if(isset($_GET["u"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
}
$sql = "SELECT users.*, weighthistory.* FROM users JOIN weighthistory USING(id)";
$user_query = mysqli_query($db_conx, $sql);
// check if the user exists in the database
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$id = $row ["id"];
$username = $row ["username"];
$weight = $row["weight"];
$weighthist = $row["weighthist"];
$point_hist = $row["point_hist"];
}
// this is to calculate points score
$calweight = $weight - $weighthist;
$points = $calweight * 10;
$result = mysql_query('SELECT SUM (point_hist) AS value_sum FROM points_history');
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
?>
THIS IS THE HTML:
<div><b>Point Hist: </b> <?php echo $sum; ?> </div>
<input id="point_hist" type="hidden" name="point_hist" value="<?php echo $sum; ?>" readonly/>
</html>
I managed to figure it out, thanks for the tips here is the final result of my query etc...
$res = mysqli_query($db_conx,'SELECT sum(point_hist) FROM points_history');
if (FALSE === $res) die("Select sum failed: ".mysqli_error);
$row = mysqli_fetch_row($res);
$sum = $row[0];

Php Game Sql Problems

I need help with this code, i need it to add an array in Gangs
under members and seperate them with -
I need every member in the Gang to be listed under Members and separated with -
so i can explode them below.
This is the line that adds the members to gangs but its without - and i think it erases members that are already there.
$result = mysql_query("UPDATE Gangs SET members='".$name."'WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'")
or die(mysql_error());
full code
if(isset($_POST['creategang'])){
if(empty($_POST['gang_name'])){
echo "Enter a Gang Name.";
} else {
if (strlen($_POST['gang_name']) > "20"){
echo "The username may not consist out of more then 20 characters.";
}else{
if (ereg('[^A-Za-z0-9]', $_POST['gang_name'])) {
echo "Invalid Name only A-Z,a-z and 0-9 is allowed.";
}else{
$sql = "SELECT name FROM Gangs WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$m_count = mysql_num_rows($query);
if($m_count >= "1"){
echo 'This name has already been used.!';
}else{
$sql = "INSERT INTO Gangs SET name = '".$_POST['gang_name']."' , owner= '$name'";
$res = mysql_query($sql);
$result = mysql_query("UPDATE users SET gang='".mysql_real_escape_string($_POST['gang_name'])."' WHERE id='" .mysql_real_escape_string($_SESSION['user_id']). "'")
or die(mysql_error());
$result = mysql_query("UPDATE Gangs SET members='".$name."'WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'")
or die(mysql_error());
echo 'Gang successfully created!';
}
}
}
}
}
?>
this is the code i will use to separate the array
$Gang_array = explode("-", $Gang_members);
Thanks for viewing my question and thanks in advance for helping me
new code to add to gang
<? include_once("connect.php"); ?>
<?
if(isset($_SESSION['user_id'])) {
// Login OK, update last active
$sql = "UPDATE users SET lastactive=NOW() WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'";
mysql_query($sql);
}else{
header("Location: index.php");
exit();
}
$sql = "SELECT * FROM users WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$id = htmlspecialchars($row->id);
$userip = htmlspecialchars($row->userip);
$name = htmlspecialchars($row->name);
$sitestate = htmlspecialchars($row->sitestate);
$password = htmlspecialchars($row->password);
$mail = htmlspecialchars($row->mail);
$money = htmlspecialchars($row->money);
$exp = htmlspecialchars($row->exp);
$rank = htmlspecialchars($row->rank);
$health = htmlspecialchars($row->health);
$points = htmlspecialchars($row->points);
$profile = htmlspecialchars($row->profile);
$gang = htmlspecialchars($row->gang);
?>
<?php
$sql = "SELECT * FROM Gangs WHERE name='".mysql_real_escape_string($_GET['name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$Gang_name = htmlspecialchars($row->name);
$Gang_owner = htmlspecialchars($row->owner);
$Gang_money = htmlspecialchars($row->money);
$Gang_exp = htmlspecialchars($row->exp);
$Gang_level = htmlspecialchars($row->level);
$Gang_members = htmlspecialchars($row->members);
$Gang_array = explode("-", $Gang_members);
$Gang_profile = htmlspecialchars($row->profile);
?>
<div id="content" class="profile">
<h2>Gang Profile</h2>
<form method="post" >
<input type="submit" name="Petition" id="Petition" value="Petition">
</form>
<center>
<h1><?php echo $Gang_name; ?></h1>
Owner: <?php echo $Gang_owner; ?><br>
Gang Cash: $<?php echo $Gang_money; ?><br>
Gang Exp: <?php echo $Gang_exp; ?><br>
Gang Level: <?php echo $Gang_level; ?><br>
Gang Members: <?php echo $Gang_array; ?><br>
</center><br>
<p>Gang Quote</p>
<div id="UserText">
<?php
$Gang_profile = htmlentities($Gang_profile);
$Gang_profile = nl2br($Gang_profile);
$Gang_profile = stripslashes($Gang_profile);
echo $Gang_profile; ?>
</div>
</div>
<?
if (isset($_POST['Petition'])) {
$result = mysql_query("SELECT members FROM Gangs
WHERE name='".$Gang_name."'");
if ($result) {
while($row = mysql_fetch_assoc($result)) {
$members = $row['members'];
}
}
if ($members != '') $members .= '-'.$name;
else $members = $name;
$result = mysql_query("UPDATE Gangs SET members='".$members."' WHERE name='".$Gang_name."'");
}
If I understand your question correctly. You can try this :
Get the members first :
$result = mysql_query("SELECT members FROM Gangs
WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'");
if ($result) {
while($row = mysql_fetch_assoc($result)) {
$members = $row['members'];
}
}
Then add new member and do update :
//This is to check whether $name is already in the gangs
if (strpos($members,$name) !== false) {
if ($members != '') $members .= '-'.$name;
else $members = $name;
//Update to gangs
$result = mysql_query("UPDATE Gangs SET members='".$members."' WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'");
}
else sprintf("%s is in the gangs already",$name);
Hope it helps.
Pseudo code, but this should probably work:
$result = mysql_query("UPDATE Gangs SET members = members + '-' + '".$name."'WHERE name='".mysql_real_escape_string($_POST['gang_name'])."'")
or die(mysql_error());

Categories