I want to make a shop for my website, so I need MySQL.
I want to take 50 Golds from the user, and give 5 atkdmg.
My current script looks like this:
<?php
ob_start();
session_start();
print('<meta http-equiv="content-type" content="text/html; charset=UTF-8"
/>');
include('config.php');
if(isset($_SESSION['rank']) && $_SESSION['rank'] >= 1)
{
if(isset($_SESSION['Gold']) && $_SESSION['Gold'] >= 50)
{
mysql_query("UPDATE users SET Gold = $_SESSION[Gold]-50 WHERE id =
$_SESSION[id];");
mysql_query("UPDATE users SET AtkDmg = $_SESSION[AtkDmg] + 5' WHERE id =
$_SESSION[id];");
} else header('location: shop.php');
} else header('location: login.php');
mysql_close()
?>
What is session? here it is:
<?php
ob_start();
session_start();
include('config.php');
include('login_form.php');
if(isset($_POST["login"])){
$nickname = $_POST["nickname"];
$password = md5($_POST["password"]);
$lekerdezes = mysql_query("SELECT * FROM users WHERE nickname =
'".mysql_real_escape_string($nickname)."' AND password = '$password'");
$vanelekerdezes = mysql_num_rows($lekerdezes);
if ($vanelekerdezes>0)
{
header('location: login.php');
$adatok=mysql_fetch_assoc($lekerdezes);
$_SESSION["id"]=$adatok["id"];
$_SESSION['bann'] = 0;
$_SESSION["nickname"]=$adatok["nickname"];
$_SESSION["rank"]=$adatok["rank"];
$_SESSION["Gold"]=$adatok["Gold"];
$_SESSION["AtkDmg"]=$adatok["AtkDmg"];
}
else
{
print 'Hibás felhasználónév vagy jelszó!';
print mysql_error();
}
} else if(isset($_SESSION["nickname"])){
header('location: home.php');
}
?>
I hope you can help me, I'm still learning PHP, so maybe that's why I can't fix this simple thing... So if you would write: learn PHP, I'm already doing that :)
First, adjust the session var:
$gold = $_SESSION['Gold'] = $_SESSION['Gold'] - 50;
$attackDamage = $_SESSION['AtkDmg'] = $_SESSION['AtkDmg'] + 5;
Edit your SQL strings like this:
"UPDATE users SET AtkDmg = $attackDamage etc etc
Related
I have a quiz system where if the correct answer is chosen, the score will +1. But I clicked backspace once, and the score won't reset to 0 everytime I backspace. I tried re-answering the question, but the score is still kept and won't start back from 0
keep in mind tho i used 'skor' instead of 'score'
<?php
require 'connect.php';
//GET SUBJECT ID
session_start();
$topikpilihan=$_SESSION['topikpilihan'];
?>
<?php session_start(); ?>
//CHECK SCORE
<?php
if (!isset($_SESSION['skor'])){
$_SESSION['skor'] = 0;
}
//WHEN THE SELECTED ANSWER IS POSTED
if($_POST){
$idsoalan = $_POST['idsoalan'];
$number = $_POST['number'];
$selected_choice = $_POST['pilihan'];
$nextsoalan=$number+1;
$totalsoalan=4;
//GET TOTAL QUESTIONS
$query="SELECT * FROM soalan where idtopik= '$topikpilihan'";
$result1 = mysqli_query($condb,$query);
$totalsoalan=mysqli_num_rows($result1);
//GET CORRECT ANSWER
$query2 = "SELECT * FROM soalan WHERE nosoalan = $number AND idsoalan=$idsoalan";
$result2 = mysqli_query($condb,$query2);
$row = mysqli_fetch_assoc($result2);
$correct_choice=$row['jawapansoalan'];
//COMPARE SELECTED ANSWER AND CORRECT ANSWER
if($correct_choice == $selected_choice){
$semakan="TEPAT";
$_SESSION['skor']++;
}
if($number == $totalsoalan){
header("Location: jawabsoalan-tamat.php");
exit();
} else {
header("Location: jawabsoalan-mula.php?semakan=".$semakan."&idtopik=".$topikpilihan."&n=".$nextsoalan."&skor=".
$_SESSION['skor']);
}
}
?>
I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */
I used to store all my data in 000webhost, today I decided to move to hostinger. So.. after moving it I replaced the old mysql_connect info by the new one. Alright, after doing that I tested it, everything has ran fine, except some echo functions.
check file (connects to the server and do the login):
<?php
$servidorr = "mysql.XXXX.co.uk";
$bdd = "XXXXXXXX";
$usuarioo = "XXXXX";
$senhaa = "XXXXXXX";
if (!empty($_POST) AND (empty($_POST['usuario']) OR empty($_POST['senha']))) {
header("Location: geton"); exit;
}
mysql_connect($servidorr, $usuarioo, $senhaa) or trigger_error(mysql_error());
mysql_select_db($bdd) or trigger_error(mysql_error());
$usuario = mysql_real_escape_string($_POST['usuario']);
$senha = mysql_real_escape_string($_POST['senha']);
$lang = mysql_real_escape_string($_POST['lang']);
$sql = "SELECT `id`, `nome`, `nivel` FROM `usuarios` WHERE (`usuario` = '". $usuario ."') AND (`senha` = '". sha1($senha) ."') AND (`ativo` = 1) LIMIT 1";
$updatelang = "UPDATE usuarios SET lang='$lang' WHERE usuario='$usuario'";
$query = mysql_query($sql);
if (mysql_num_rows($query) != 1) {
echo "<script>alert('Oops! Looks like there is something wrong with your login! *perhaps a typo or you did not fill out the fields*'); location.href='geton'</script>"; exit;
} else {
$resultado = mysql_fetch_assoc($query);
mysql_query($updatelang);
if (!isset($_SESSION)) session_start();
$_SESSION['UsuarioID'] = $resultado['id'];
$_SESSION['UsuarioNome'] = $resultado['nome'];
$_SESSION['usuario'] = $resultado['usuario'];
$_SESSION['UsuarioNivel'] = $resultado['nivel'];
$_SESSION['lang'] = $resultado['lang'];
header("Location: http://mapmaking.zz.mu/pages/home"); exit;
}
?>
Home file (these echos are just for testing and this is not the original file, the original one has the same php stuff, except the echo functions, those are in random lines):
<?php
if (!isset($_SESSION)) session_start();
$tlang = $_SESSION['UsuarioLang'];
$aclevel = $_SESSION['UsuarioNivel'];
$nick = $_SESSION['UsuarioNome'];
$neededal = 1;
if (!isset($_SESSION['UsuarioID']) OR ($_SESSION['UsuarioNivel'] < $neededal)) {
session_destroy();
header("Location: http://inside.mapmaking.uk.to/geton"); exit;
}
session_start();
echo $tlang;
echo $aclevel;
echo $nick;
echo "$level$tlang$tlang";
?>
[this one basically start the session and check if the connected user acess level is 1]
Echo $tlang does not work! :( somehow it doesn’t, I have no idea why ;_;
Hope you guys help me, thank you!!
$_SESSION['lang'] != $_SESSION['UsuarioLang']
You assign a value to the first one, yet expect value from the second one.
$_SESSION['lang'] = $resultado['lang'];
$tlang = $_SESSION['UsuarioLang'];
Change this line:
$_SESSION['lang'] = $resultado['lang'];
to the following:
$_SESSION['UsuarioLang'] = $resultado['lang'];
You should also call session_start() without the isset check. Also, you should consider using && instead of AND and || instead of OR, as PHP has weird operator precedence rules (the assignment = has a higher precendence than either AND or OR).
I'm stumped on this one. Very simple login screen. When there is a password match the script works perfectly and jumps to main.php. When the uname or pswd is wrong, the script wont drop into the ELSE clause and wont go to badlogin.php. The script just hangs with the blank white screen.
any help would be great.
<?php
include("dbconnect.php");
$u_name = mysql_real_escape_string($_POST['uname']);
$p_word = mysql_real_escape_string($_POST['pword']);
# *** querying all records ***
$query = mysql_query("SELECT * FROM notes_users WHERE valid_password = '$p_word' && valid_username = '$u_name'");
while($rst = mysql_fetch_array($query)) {
if (($rst[valid_username] == $u_name) AND ($rst[valid_password] == $p_word)) {
session_start();
$_SESSION['login'] = "1";
header('Location: main.php') ;
} else {
session_start();
$_SESSION['login'] = '';
header('Location: badlogin.php') ;
}
}
?>
If there's no results returned from the query then "while($rst = mysql_fetch_array($query))" will never prove true, and the while loop is skipped over entirely.
edit: You could change it to a "do while" or just fix your while conditional.
You should have quotes around valid_username and valid_password. Right now, you are using them as constants. And you don't need the loop and if to check if the pair matches, you're already checking that on your query. I think your problem may be that you are comparing the values from the db with escaped values when you do that second comparison. Wiseguy and VDH are right, you never enter the while when the query returns false. Anyway, this simpler version should address all these issues:
<?php
session_start();
include("dbconnect.php");
$u_name = mysql_real_escape_string($_POST['uname']);
$p_word = mysql_real_escape_string($_POST['pword']);
# *** querying all records ***
$query = mysql_query("SELECT * FROM notes_users WHERE valid_password = '$p_word' AND valid_username = '$u_name'");
if(mysql_num_rows($query) > 0) {
$_SESSION['login'] = "1";
header('Location: main.php') ;
} else {
$_SESSION['login'] = '';
header('Location: badlogin.php') ;
}
?>
Here are some changes, you should not loop through the result if your only expecting a match:
<?php
//Session start at the top
session_start();
include("dbconnect.php");
$u_name = mysql_real_escape_string($_POST['uname']);
$p_word = mysql_real_escape_string($_POST['pword']);
# *** querying all records ***
//Some changes, use a LIMIT clause unless your expecting multiple users
//And as your only checking for row existence there no need to return *
//And never have plain txt passwords in db, use at least sha1 and not md5
$query = mysql_query('SELECT 1
FROM notes_users
WHERE valid_password ="'.sha1($p_word).'" && valid_username = '.$u_name.'" LIMIT 1');
//assoc
$rst = mysql_fetch_assoc($query);
//User found
if(mysql_num_rows($rst)==1){
$_SESSION['login'] = true;
header('Location: ./main.php');
die;
}else{
//User not found
$_SESSION['login'] = false;
header('Location: ./badlogin.php');
die;
}
?>
I am trying to check if the session username matches the record in my database and if it does, I want to include a file.
This is my code
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT * FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez)
{
include('check.php');
}
else
{
echo "error";
}
?>
The session username does not match the record in my database, yet the file is being included. Why?
OH, I FOUND THE ISSUE. IT IS CONSIDERING MY USERNAME TO BE ROOT...BUT WHEN I SAY ECHO $_SESSION['USERNAME'] IT IS CRAIG#CRAIG.COM..WHY SO>
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT sessionusername FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez["sessionusername"]==$username)
{
include('check.php');
}
else
{
echo "error";
}
?>
You are simply testing whether the array $geez is empty or not. If the array has anything in it, you if($geez) will return true. To stop this behaviour, please see ceteras' answer, particularly this part:
if($geez["sessionusername"]==$username)
{
include('check.php');
}
I believe that's the only part that has changed.
Thanks,
James