retrieve data from database that is updated - php

I've already made calculation for BMI and I can update height(will update weight soon) if user getting taller or shorter. The problem is, after I already update the height I cannot update BMI and BMI STATUS(underweight, normal, obese) which is a big problem for me..
This is my coding for php
if(!isset($_SESSION['user']))
{
header("Location: PHOME.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
if(isset($_POST['updateH']))
{
$height = $_POST['height'];
$weight = $_SESSION['user'];
$sex = $_SESSION['user'];
$bmiresult = $_SESSION['user'];
$bmi = $weight/(($height/100)*($height/100));
if ($sex=="female")
{
if ($bmi <= 19)
$bmiresult="underweight!";
else if ($bmi>19 && $bmi<= 25)
$bmiresult="normal";
else if ($bmi > 25 && $bmi<= 30)
$bmiresult="overweight!";
else if ($bmi>30)
$bmiresult="OBESE!";
}
else if ($sex=="male")
{
if ($bmi <= 20)
$bmiresult="underweight!";
else if ($bmi>20 && $bmi<= 25)
$bmiresult="normal";
else if ($bmi > 25 && $bmi<= 30)
$bmiresult="overweight!";
else if ($bmi>30)
$bmiresult="OBESE!";
}
$sql = "UPDATE users SET height = $height, weight = $weight,
bmi = $bmi, bmiresult = '$bmiresult'
WHERE user_id=" . $_SESSION['user'];
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "<script type='text/javascript'>alert('Update Successfully!')</script>";
} else {
echo mysql_error();
}
}
This is my form which I am using bootstrap
<form method="post" action="<?php $_PHP_SELF ?>">
<h3> Height : <?php echo $userRow['height']; ?> cm</h3>
<input type="text" class="small" name="height" id="height" placeholder="Update Height CM"/>
<button type="submit" class="btn btn-warning" name="updateH"> UPDATE </button>

You appear to be trying to get everything about the user from the SESSION and I assume that information is not there. However, you read the users current data from the database, so all the existing values are available to you in $userRow so use those and your calculation will probably work.
Sidenote: Make sure the session has been started, and for all pages using sessions.
if(!isset($_SESSION['user']))
{
header("Location: PHOME.php");
exit; // stop further execution
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
if ( ! $res ) {
echo 'cannot find user ' . mysql_error();
}
$userRow=mysql_fetch_array($res);
if(isset($_POST['updateH']))
{
// if new data is supplied in $_POST use it,
// otherwise use the existing userRow values
$height = isset($_POST['height']) ? $_POST['height'] : $userRow['height'];
$weight = isset($_POST['weight']) ? $_POST['weight'] : $userRow['weight'];
$sex = $userRow['sex'];
$bmiresult = $userRow['bmiresult '];
//recalc BMI
$bmi = $weight/(($height/100)*($height/100));
if ($sex=="female")
{
if ($bmi <= 19)
$bmiresult="underweight!";
else if ($bmi>19 && $bmi<= 25)
$bmiresult="normal";
else if ($bmi > 25 && $bmi<= 30)
$bmiresult="overweight!";
else if ($bmi>30)
$bmiresult="OBESE!";
}
else if ($sex=="male")
{
if ($bmi <= 20)
$bmiresult="underweight!";
else if ($bmi>20 && $bmi<= 25)
$bmiresult="normal";
else if ($bmi > 25 && $bmi<= 30)
$bmiresult="overweight!";
else if ($bmi>30)
$bmiresult="OBESE!";
}
$sql = "UPDATE users ".
"SET height = $height ".
"SET bmi = $bmi".
"SET bmiresult = $bmiresult".
"WHERE user_id=".$_SESSION['user'];
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "<script type='text/javascript'>alert('Update Successfully!')</script>";
} else {
echo mysql_error();
}
}
As you are obviously just starting out on your PHP journey, please do not waste your time learning the mysql_ database extension as it is soon to be removed from PHP. Instead, spend your time learning either the mysqli_ or PDO extensions. See here for help deciding which Its quite a good read.

Your update statement should read:
$sql = "UPDATE users ".
"SET height = $height ".
" , bmi = $bmi".
" , bmiresult = $bmiresult".
"WHERE user_id=".$_SESSION['user'];
$result=mysql_query($sql);

Related

How to check if card pin have been used?

I am building a student result portal and I want each pin to one student for 5 times.
Here is my code:
if (!$error) {
$res=mysql_query("SELECT * from pin WHERE userid='$reg'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if regno correct it returns must be 1 row
if( $count == 1 && $row['userid']==$reg ) {
$pinid = $row['id'] ;
$check_hw = $row['hw'] ;
if ($check_hw <=4 ) {
$res=mysql_query("UPDATE pin SET userid='$reg',status='1',hw=hw+1 WHERE pin='$pin'");
$_SESSION['user'] = $row['userid'];
header("Location: access.php");
} else {
$errMSG = "Card Limit Exceeded";
}
} else {
$errMSG = "Card Used By Another user Or Limit Exceeded";
}
}
this what i want to do please help
if(user enter pin){
select status from pins where pin = pin
if(status = "used" or pin is tied to a different ID other that the student ID entered){
echo " card used and buy new scratch card "
header('Location: buypin.php');
}
else{
header('Location: rightplace.php');
set the status of this pin to "used" and tie that very pin to the students ID
}
}
i did rewrite the code to
if (!$error) {
$res=mysql_query("SELECT id,userid,hw FROM pin WHERE userid=" . (int)$reg);
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if regno correct it returns must be 1 row
if ($row = mysql_fetch_array($res)) {
$pinid = $row['id'] ;
$check_hw = $row['hw'] ;
if ($check_hw <=4 ) {
$res=mysql_query("UPDATE pin SET userid='$reg',status='1',hw=hw+1 WHERE pin='$pin'");
$_SESSION['user'] = $row['userid'];
header("Location: access.php");
}
else {
$errMSG = "Card Limit Exceeded";
}
} else {
$errMSG = "Card Used By Another user ";
}
}
my working code
if( isset($_POST['btn-signup']) ){
$reg = trim($_POST['reg']);
$reg = strip_tags($reg);
$reg = htmlspecialchars($reg);
$pin = trim($_POST['pin']);
$pin = strip_tags($pin);
$pin = htmlspecialchars($pin);
$res=mysqli_query($con,"SELECT * FROM pin WHERE pin ='$pin'");
$row=mysqli_fetch_array($res);
$check_id = $row['userid'];
// checking if the colum userid is empty
if ('' !== $row['userid']){
// if userid colum is not empty,reg no is correct and limit more than 4
if ($row['userid']==$reg && $row['hw']<=4) {
$errMSG = "log";
}else {
$errMSG = " Card Used Or Limit Exceeded";
}
}else{
$errMSG = "log";
}
}
?>
Thanks alot

Php/Mysql process with user & admin privilege issue

I have this weekly countdown process and if a login user reaches the 0 weeks limit his page will be banned from the site and that's fine, my problem is if i'm the admin i don't want this process to ban me.
On this platform i have user and admin privileges
like this: For admin: $user->isAdmin() and for the user : if($user->islg()
The Php process is this:
if($user->islg()) {
function get_weeks_remaining($date, $expire){
$difference = strtotime($expire) - strtotime($date);
return floor($difference / 604800);
}
$link = mysqli_connect("localhost", "user", "password", "table");
$nume = $user->data->username;
$id = $user->data->id;
$date = date('m/d/Y h:i:s a', time());
$expire_date = 'May 14, 2016';
$remain = get_weeks_remaining($date, $expire_date);
$reason = 'user has been suspended';
// weeks remaining
$save=mysql_query("INSERT INTO `week-ferify`(`id`,`date`,`name`,`expire`,`remain`)VALUES('$id','$date','$name','$expire_date','$remain')");
$sql = "SELECT `id`,`remain` FROM `week-ferify`";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while(list($id,$remain) = mysqli_fetch_array($result)){
if($remain > 0 and $remain < 2){
echo "<div class=\"week-remain-box\"><span class='week-remain-text'>week remain</span><p class='week-remain-remain'>$remain</p></div>";
}else{
echo "<div class=\"week-remain-box\"><span class='week-remain-text'>weeks remains</span><p class='week-remain-remain'>$remain</p></div>";
//Ban process
} if ($remain > 0 and $remain < 2) {
mysql_query("UPDATE `mls_users` SET banned=0 WHERE id=$id");
} else {
mysql_query("UPDATE `mls_users` SET banned=1 WHERE id=$id");
mysql_query("INSERT INTO `mls_banned`(`id`,`until`,`by`,`reason`)VALUES('$id','1462317824','1','$reason')");
}
}
mysqli_free_result($result);
}
}
}
I don't know where to put $user->isAdmin() for not being banned by the process and only simple users to get banned. Thanks for any advice, and sorry for my bad english.
Given that the $user->isAdmin() method returns true or false based on whether the user is an administrator:
Place an if statement before the actual ban code.
//Ban process
if ($remain > 0 and $remain < 2) {
mysql_query("UPDATE `mls_users` SET banned=0 WHERE id=$id");
} else {
if(!$user->isAdmin()){
mysql_query("UPDATE `mls_users` SET banned=1 WHERE id=$id");
mysql_query("INSERT INTO `mls_banned`(`id`,`until`,`by`,`reason`)VALUES('$id','1462317824','1','$reason')");
}
}
However, if you can safely assume that the default setting for banned is 0. I suggest you place wrap the condition over the entire "banning code"
//Ban process
if(!$user->isAdmin()){
if ($remain > 0 and $remain < 2) {
mysql_query("UPDATE `mls_users` SET banned=0 WHERE id=$id");
} else {
mysql_query("UPDATE `mls_users` SET banned=1 WHERE id=$id");
mysql_query("INSERT INTO `mls_banned`(`id`,`until`,`by`,`reason`)VALUES('$id','1462317824','1','$reason')");
}
}
And also you should probably modify the counter too.

validation php not working?

The following is the email verification code for my site.
The verification url sent to the user's email is as follows:
http://www.mywebsite.com/valid.php?confr=2774405&userid=2
Extra notes :
1) key is a column in my database which gets a random value on registration.
2) if $verify == 1 and password_in_db=== user_entered_password, then login takes place in the login page.
<?php
include 'connect.php';
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$_GET['userid']'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1") {
echo "Link Expired . Go to our login page :";
} else {
if (isset($_GET["confr"]) && isset($_GET["userid"])) {
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2) {
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$_GET["userid"]' ;");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
} else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Code for connect.php
<?php
mysql_connect("host", "username", "pass"); //connects to the server
mysql_select_db("database_name"); //selects the database
?>
The problem is that it is giving me a blank screen .
i believe the error lies in the sql
when ever i use a "WHERE" statement i always define as a variable, try this
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
also, you have a semi colon in the insert sql
Try this.......
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
while ($details = mysql_fetch_assoc($query)){
$verify = $details['verify'];
$confirm2 = $details['key'];
}
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Note: insert statement has no where - as long as you dont use "insert into select..."
http://dev.mysql.com/doc/refman/5.1/de/insert.html

Upvote/Downvote System

I have the following PHP script:
<?php
$vote_type = $_GET['type'];
$book = $_GET['book'];
$id = $_GET['id'];
include 'pagehead.php';
$tracker_table = $book.'VoteTrack';
$username = $_SESSION['username'];
session_start();
if ($_SESSION['username'] == null) {
echo 'You must be logged in to vote';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
}
include 'mysqlserver.php';
$con = mysql_connect($mysql_host, $mysql_username, $mysql_password);
if (!$con){
die ('Failed to connect to the database');
}
mysql_select_db("a6595899_s", $con);
$data_query = "SELECT * FROM $book WHERE id=$id";
$lesson_data = mysql_query($data_query);
$lesson_array = mysql_fetch_assoc($lesson_data);
$vote_cop_query = "SELECT * FROM $tracker_table WHERE user='$username' AND id=$id";
$vote_cop_data = mysql_query($vote_cop_query);
$vote_cop = mysql_fetch_assoc($vote_cop_data);
if (mysql_num_rows($vote_cop_data) != 0 && $vote_type == 'up' && $vote_cop['has'] == 1) {
echo 'You have already upvoted this lesson.';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
} elseif (mysql_num_rows($vote_cop_data) != 0 && $vote_type == 'down' && $vote_cop['has'] == 2) {
echo 'You have already downvoted this lesson.';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
}
$vote_count = $lesson_array['votes'];
if ($vote_type == 'up') {
$vote_count++;
$has_type = 1;
} elseif ($vote_type == 'down') {
$vote_count--;
$has_type = 2;
} else {
die('Vote type not specified.');
}
$new_or = mysql_num_rows($vote_cop_data);
if ($new_or == 0) {
$track_query = "INSERT INTO $tracker_table (user, id, has)
VALUES ('$username', $id, $has_type)";
} else {
$track_query = "UPDATE $tracker_table SET has=$has_type WHERE user='$username' AND id=$id";
}
mysql_query($track_query);
//actually cast vote..
$update_query = "UPDATE $book SET votes=$vote_count WHERE id=$id";
mysql_query($update_query);
echo 'Your vote has been submitted!';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo'</a>';
?>
It's a very simple vote-up/and vote-down system. Unfortunately, it breaks down in certain scenarios. Let's say I'm reading a lesson that I think is good, so I vote it up. Later, I realize that the lesson is actually awful, so I downvote it. After I upvoted it the first time, the lesson had one point. After I downvote it, it has 0 again. Logic dictates that I should be able to downvote the lesson again, giving it -1 points. My code will not allow this, as my script simply says that the same action isn't allowed 2 times in a row.
What math do I use to fix this?
The problem is here where you're updating a user's activity after having downvoted their own upvote.
$track_query = "UPDATE $tracker_table SET has=$has_type WHERE user='$username' AND id=$id";
What you -should- be doing, is removing the record from the table instead of updating it, then go on to modify the score as you already are. That way, the next vote you do will be the 'first' vote you've done.
Alternatively, you could have a third vote_cop type called 'nullify' or 'revoke' or something then modify the vote cop accordingly.
See my suggestion below:
$hasVotedBefore = mysql_num_rows($vote_cop_data) != 0;
if ($hasVotedBefore) {
switch ($vote_cop_data['has']) {
case 0:
$vote_cop_type = 'revoked'; // Not really neccessary to do this, but just here for show.
break;
case 1:
$vote_cop_type = 'up';
break;
case 2:
$vote_cop_type = 'down';
break;
default:
break;
if ($vote_type == $vote_cop_type) { // We're here because we voted before and our new vote is the same as the old one.
if ($vote_type == 'up') {
echo 'You have already upvoted this lesson.';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
} elseif ($vote_type == 'down') {
echo 'You have already downvoted this lesson.';
echo '<br>';
echo '<a href="lesson.php?book='.$book.'&id='.$id.'">';
echo 'Return to lesson';
echo '</a>';
die();
}
} else { // Were here because we've voted before, and our new vote is the opposite of the old vote.
// Update vote_cop row in the database so the 'has' column is 0 (value of a revoked vote)
// This way, for future votes, we know the user has voted before, but revoked their vote.
$track_query = "UPDATE $tracker_table SET has=0 WHERE user='$username' AND id=$id";
mysql_query($track_query);
}
} else { // We're here because we never voted before.
$track_query = "INSERT INTO $tracker_table (user, id, has) VALUES ('$username', $id, $vote_type)";
mysql_query($track_query);
}
// TODO: actually cast vote..

No results returned for elseif PHP query

I have a database with a 'status' column which either reads 'active' or 'inactive'.
I'd like to return different text depending on whether the status is 'active' or 'inactive', and I'm using if... and elseif... for this.
If the status is 'active', the message is displaying perfectly. This also prompts the database to update the status field to 'inactive' - again, this is working perfectly.
But if I reload the page, using a key for which I know the status is 'inactive', nothing displays.
<?php
if (isset($_GET['key'])) {
$key = $_GET['key'];
include("db.php");
$download_query="SELECT * FROM sales WHERE key='$key'";
$download_result=#mysql_query($download_query);
$download_row=#mysql_fetch_array($download_result, MYSQL_ASSOC);
$productid=$download_row['productid'];
$datecreated=$download_row['datecreated'];
$dateaccessed=$download_row['dateaccessed'];
$status=$download_row['status'];
if ($status=="active") {
$download_updatestatus_query="UPDATE `sales` SET `status`='inactive' WHERE `key`='$key'";
$download_updatestatus_result=#mysql_query($download_updatestatus_query) or die (mysql_error());
echo "Go ahead and download file.";
}
else if ($status=="inactive") {
echo "You may have downloaded this before.";
}
}
else {
echo "Sorry, no key provided.";
}
?>
You have an extra } after your elseif. try:
else if ($status=="inactive") {
echo "You may have downloaded this before.";
}
else {
You suppose to make sure that mysql_query is not false and contains some results by running mysql_num_rows before you start fetching data.
Also passing $_GET value to MySQL Query without validation is very bad idea.
if (isset($_GET['key']))
{
//You have to make sure that provided value is safe to use in mysql query
$key = mysql_real_escape_string($_GET['key']);
include("db.php");
$download_query = "SELECT * FROM sales WHERE key='$key'";
$download_result = mysql_query($download_query);
// Check result
if (!$download_result)
die('Invalid query: ' . mysql_error());
if($download_result && mysql_num_rows($download_result) > 0)
{
$download_row = mysql_fetch_assoc($download_result);
$productid = $download_row['productid'];
$datecreated = $download_row['datecreated'];
$dateaccessed = $download_row['dateaccessed'];
$status = $download_row['status'];
if ($status == "active")
{
$download_updatestatus_query = "UPDATE `sales` SET `status`='inactive' WHERE `key`='$key'";
$download_updatestatus_result = mysql_query($download_updatestatus_query) or die (mysql_error());
echo "Go ahead and download file.";
}
else if ($status == "inactive")
{
echo "You may have downloaded this before.";
}
}
else
{
echo 'No results found';
}
}
else
{
echo "Sorry, no key provided.";
}

Categories