So, I know my code was working and I have tried un-doing all steps to see where the bug is, but I am still keep getting an error
my php id=0.
Can you guys show me how I can fix my code up?
The error is as follows:
undefined variable list_id. It works on my localmachine but not when
uploaded to server.
Thanks.
The following is my code:
if(!empty($_GET['id'])){
$list_id = intval(($_GET['id']));
try {
$sql = 'SELECT * FROM items where id =' . $list_id;
$query = $pdo->prepare($sql);
$query->execute();
} catch(Exception $e) {
echo $e->getMessage();
die();
}
$list = $query->fetch(PDO::FETCH_ASSOC);
if ($list == FALSE) {
header("location: index.php");
}
}
if ($list_id == 0) {
header("location: index.php");
}
Seems there are a few issues here. I have added the comments inline.
if(!empty($_GET['id'])){
$list_id = intval($_GET['id']); //was double parenthesis here
try {
$sql = 'SELECT * FROM items where id =' . $list_id;
$query = $pdo->prepare($sql);
$query->execute();
} catch(Exception $e) {
echo $e->getMessage();
die();
}
$list = $query->fetch(PDO::FETCH_ASSOC);
$count = count($list); //count result and use for comparison instead of false
if ($count === 0) {
header("location: index.php");
exit;
}
} else {
header("location: index.php"); //if no $_GET, redirect
exit;
}
All you need to do is instantiate the variable $list_id :
$list_id = 0; // <-- HERE
if(!empty($_GET['id'])){
$list_id = intval(($_GET['id']));
...
...
It looks as though you want to redirect to the index if there is no id parameter. Since you already check for its presence, redirect in the else clause. Remove the last block and add:
else
{
header("location: index.php");
exit;
}
You may want to add exit; after the header() call in the if block as well, so that code that uses the database further down isn't executed.
Related
I am new to...well everything. Bear with me.
I have a website that has a textbox for user input ( a code they receive). When they submit, it sends the code to a PHP file, which then checks the code against a database. If it matches the winner code, it redirects the user to a specific page. Losers, are redirected to a loser page.
That works!
However, I'm now trying to redirect users to a third page, if their code matches a different table of codes, but I can't figure out the if else statements. Can anyone help a poor doodle like myself? Thanks!
Here's what I got:
// Connect to your MySQL database
$dbhst = "localhost";
$dbnme = "blah";
$bdusr = "blaaah";
$dbpws = "blahblahblacksheep";
// Using PDO to connect
$conn = new PDO('mysql:host='.$dbhst.';dbname='.$dbnme, $bdusr, $dbpws);
// Getting variables
$answer = $_POST['answer'];
$questionID = $_POST['questionID'];
// Comparing answers
try {
$stmt = $conn->prepare("SELECT * FROM Winners WHERE Winners='" . $answer . "' LIMIT 0,1");
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
// echo 'Congrats, you've entered a correct code';
header("Location: https://get-a-brik.myshopify.com/pages/8522");
}
} else {
// echo 'Your code did not win. Please try again.';
header("Location: https://get-a-brik.myshopify.com/pages/5551");
exit;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
You can use an if ... else if ... else statement:
if (... user is winner ...) {
header("Location: https://get-a-brik.myshopify.com/pages/8522");
} else if (... user is looser ...) {
header("Location: https://get-a-brik.myshopify.com/pages/5551");
} else {
header("Location: winner page");
}
In most cases, a plain URL will be recognized as such and automatically linked:
The error only appears on localhost, please help!
The interesting thing is that on the hostinger server it works perfectly...
require_once('header.php');
// Preventing the direct access of this page.
if(!isset($_REQUEST['slug']))
{
header('location: index.php');
exit;
}
else
{
// Check the page slug is valid or not.
$statement = $pdo->prepare("SELECT * FROM tbl_page WHERE page_slug=? AND status=?");
$statement->execute(array($_REQUEST['slug'],'Ativo'));
$total = $statement->rowCount();
if( $total == 0 )
{
header('location: index.php');
exit;
}
}
$statement = $pdo->prepare("SELECT * FROM tbl_page WHERE page_slug=?");
$statement->execute(array($_REQUEST['slug']));
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row)
{
$page_name = $row['page_name'];
$page_slug = $row['page_slug'];
$page_content = $row['page_content'];
$page_layout = $row['page_layout'];
$banner = $row['banner'];
$status = $row['status'];
}
// If a page is not Ativo, redirect the user while direct URL press
if($status == 'Inativo')
{
header('location: index.php');
exit;
}
Hey guys so i really have a problem in php and i have been working on it for like an hour and i can get it to work. So in my database i have two tables:
usuarios and menus
So each user have a menu assigned like this:
usuarios
id email ....... menus
1 email ...... 1,2,3,4
where 1,2,3,4 is text that i will explode and convert it into an array so latter i can get the menus checking the menu id's.
menus
id url .....
1 profile ..........
2 messages ..........
3 log out ..........
4 support ..........
I dont know why it is not working, please help.
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));}
// Checks the user id from his session (session has been already started in headers)
if($stmt->rowCount() > 0){
$row = $stmt->fetch();
$menus = $row['menus'];
//Gets the menus
$menus = explode(",", $menus);
//Converts the text into an array.
$i = 0;
$menusize = sizeof($menus);
//Checks how big is $menus array
$menusize = $menusize -1;
//This is because $i=0 and not 1
while ($i == $menusize) {
try{
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
$stmt->execute(array(':menus'=>$menus[$i]));
$row = $stmt->fetch();
if ($section==$row['url']) {
echo '<li class="liselected"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}else{
echo '<li class="menuelement"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
$i++;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Here is the problem, in this while
} else {
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}else{
header("Location:index.php");
}
?>
I have checked and what happends is that $i doesnt seems to be incrementing, i have been working on it but nothing seems to do it.
Thank you all for your support!
You should do it a little bit differently altogether, like storing the menu's in different rows but for now:
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
# When you set the $_SESSION['id'] and you're sure it's sanitized you don't have to prepare a query. Instead execute it directly.
# Preparing is useful for user submitted data or running the same query more then once with different values (seen below)
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
// This part of the code does not match your description of your database.
$row = $stmt->fetch();
$menu = explode(",", $row['menus']);
// end
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
try{
foreach($menu as $value){
$stmt->execute(array(':menus'=>$value));
$row = $stmt->fetch();
$css_class = ($section == $row['url']) ? 'liselected' : 'menuelement';
echo '<li class="'.$css_class.'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
} else {
header("Location:index.php");
}
?>
Please note that I only prepared the query once, this is the proper way to do it. Preparing takes server performance, but once prepared you can rebind the values.
Also, I changed the loop to a foreach loop, easier to maintain.
There where also some bracket issues in the code, my advice always code in the same way so these issues are easy to spot.
I'm currently building a system for a football league. And are currently working on the script file for adding results. Most of the script works and the result is always successfully added to the database. However the authentication part seems to fail. The if statement on line 12 does not seem to fire and I can't understand why.
My code can be found in the pastebin link here: http://pastebin.com/ty4pdGgn
<?PHP
include 'functions.php';
dbConnect();
//$userEmail = mysql_real_escape_string($_POST["userEmailText"]);
$userCode = mysql_real_escape_string($_POST["userPasscodeText"]);
$authenticated = false;
$userEmail = "info#example.com";
if ($userEmail == "info#example.com") {
header('Location: ../results.php?error=authentication');
}
$allUsers = mysql_query("SELECT * FROM accounts WHERE email = '$userEmail'");
while ($thisUser = mysql_fetch_assoc($allUsers)){
if ($userCode != $thisUser['passCode']) {
header('Location: ../results.php?error=authentication2');
}
echo $thisUser['passCode'];
$authenticated = true;
$userID = $thisUser['userID'];
}
if (!$authenticated) {
header('Location: ../results.php?error=authentication3');
}
$dateSubmitted = $_POST['submissionDate'];
$homeTeam = $_POST['homeTeam'];
$awayTeam = $_POST['awayTeam'];
$homeGoals = $_POST['homeGoals'];
$awayGoals = $_POST['awayGoals'];
if ($homeTeam == $awayTeam) {
header("Location: ../results.php?error=team");
}
if (getTeamLeague($homeTeam) != getTeamLeague($awayTeam)) {
header("Location: ../results.php?error=league");
} else {
$leagueID = getTeamLeague($homeTeam);
}
if ($homeGoals > $awayGoals) {
$winnerID = $homeTeam;
} else if ($homeGoals < $awayGoals) {
$winnerID = $awayTeam;
} else if ($homeGoals == $awayGoals) {
$winnerID = -1;
}
$cQuery = mysql_query("INSERT INTO results VALUES ('', $userID, '$dateSubmitted', $leagueID, $homeTeam, $homeGoals, $awayTeam, $awayGoals, $winnerID, 0)");
if ($cQuery){
header('Location: ../results.php');
} else {
echo mysql_error();
}
?>
Any help with this matter will be much appreciated. The functions.php contains no errors as this is all to do with database entry and not the authentication.
Put a die(); after the header("Location:...");
As your comparison code (the "if" part on line 12) that you pasted has to work, i have two advice:
Put a die(); or exit(); after the header() part.
Try looking here, as I am not sure if header() will work, while the location path you set is relative. Basic advice is to always use base paths for redirects, like "http://your.site.com/script.php").
This code only redirects to notenrolled.php even if the input value is correct. I want it to continue the process if the value entered is correct. Is there something wrong with my code?
<?php
//Setup connection to the database
$connect = mysql_pconnect("localhost", "root", "")
or die(mysql_error());
//Connect to the database
mysql_select_db("dbgis", $connect) or die(mysql_error());
$query = "SELECT * from tbl_student WHERE stud_id= '$stud_id' ";
$result = mysql_query($query);
$totalrows = mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
header("Location: yesno.php");
}
if($totalrows != 0)
{
header("Location: notenrolled.php");
}
?>
I tried the die(); and it seems to be working because it just says a redirection looping error with yesno.php. So I think I might have put the code in the wrong .php page.
The flow is like this: I have a guard.php page where I could search a query(stud_id) using my search form in the page. I then want to check whether the query exists and if it doesn't, I want it to redirect to notenrolled.php else if the query is found, I want it to proceed to yesno.php.
When you set a Location header, you ALWAYS immediately follow it with exit or die().
(Only if you truly understand what you are doing, might you not immediately use it, but at your own risk.)
if ($totalrows > 0)
{ // has results
header("Location: yesno.php");
exit(0);
}
else
{ // no result
header("Location: notenrolled.php");
exit(0);
}
You should not use while just to evaluate if there is a record.
while($row = mysql_fetch_array($result))
{
header("Location: yesno.php");
}
Your code always redirects to notenrolled.php because of the codition:
if($totalrows != 0)
{
header("Location: notenrolled.php");
}
//this block will always be true if your $totalrows is greater than 0
The solution: check $totalrows if is greater than 0
if ($totalrows > 0){
header("Location: yesno.php");
} else {
header("Location: notenrolled.php");
}
u can use php function mysql_affected_rows to see number off affected rows in SELECT,
if (mysql_affected_rows() == 0){
header("Location: notenrolled.php");
} else {
header("Location: yesno.php");
}
The correct way to do it is this:
if($totalrows>0)
header("Location: yesno.php");
else
header("Location: notenrolled.php");
try this
if($totalrows == 0)
{
header("Location: notenrolled.php");
die();
}