I have the following variable $user_id being set by
//Check if user is logged in
session_start();
if (!isset ($_SESSION['user_id']))
{
header("location:login.php");
}
elseif(isset ($_SESSION['user_id']))
{
$user_id = $_SESSION['user_id'];
}
and then within the same function file I have the following:
function course_menu()
{
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = mysql_query($sqlSubscription);
while ($rows = mysql_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
}
The problem is I keep getting undefined variable user_id every time I try to run the function. I can echo $user_id on another page lets say index.php by using require_once function.php and then echo $user_id, but for some reason the function itself can't access it?
I think it might be because it's outside its scope - but if so I'm not entirely sure what to do about it.
My question is, how can I get the function to be able to use the variable $user_id?
EDIT
So I've started doing
$user_id = $_SESSION['user_id'];
global $conn;
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = $conn->query($sqlSubscription);
while ($rows = mysqli_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
which seems to work fine, but it's a bit tedious to add a new connection each time with a function or set the $user_id manually. Is there any way around this as I have several functions that require a connection to the db to pull data. Is there a better way to structure this type of stuff? I'm not very familiar with OOP but I can try it out if I can get some direction, here's another function that I use (and there are at least another 5-6 that require db connections)
function render_dashboard()
{
$user_id = $_SESSION['user_id'];
global $conn;
//Following brings up the number of subscription days left on the user dashboard
$sqlDate = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'" ;
$date = $conn->query($sqlDate);
while ($daterows = mysqli_fetch_assoc($date))
{
$course_registered = $daterows['course_title'];
$date_time = $daterows['end_date'];
$calculate_remaining = ((strtotime("$date_time")) - time())/86400;
$round_remaining = round("$calculate_remaining", 0, PHP_ROUND_HALF_UP);
// Here we assign the right term to the amount of time remaining I.E DAY/DAYS/EXPIRED
if($round_remaining > 1)
{
$remaining = $course_registered." ".$round_remaining." "."Days Remaining";
$subscriptionStatus = 2;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining == 1)
{
$remaining = $course_registered." ".$round_remaining." "."Day Remaining";
$subscriptionStatus = 1;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining <= 0)
{
$remaining = $course_registered." "."Expired"." ".$date_time;
$subscriptionStatus = 0;
echo '<p>',$remaining,'</p>';
}
}
//Check for most recent viewed video
$sqlVideo = "SELECT `last_video` FROM users WHERE `user_id` = '".$user_id."'" ;
$videoResult = $conn->query($sqlVideo);
if ($videoRows = mysqli_fetch_assoc($videoResult))
{
$last_video = $videoRows['last_video'];
$videoLink = "SELECT `chapter_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($chapteridResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$chapter_id = $chapteridResult['chapter_id'];
}
$videoLink = "SELECT `course_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($courseResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$course_id = $courseResult['course_id'];
}
}
}
The function course_menu() will not recognize your $user_id, Since it is outside its scope.
Make use of global keyword to solve this issue.
function course_menu()
{
global $user_id;
// your remaining code .........
The solution to getting around it without using global is to either DEFINE and pass it through ie - define ('var', '$var') then function x($var) or dependency injection as stated here How can I use "Dependency Injection" in simple php functions, and should I bother?
Related
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 */
Okay, so i want this code snippet to check if variable $_GET['p'] exists in the DB, if it does then make $p = $_GET['p'], if it doesn't exist then make $p = '1', and if $_GET['p'] isn't even set in the link then just display page with id of 0 ($p = '0';). Here is my code. It only shows the "unknown page" when variable is set in the link.
if (isset($_GET['p']))
{
$getpage = $_GET['p'];
$sql = sprintf("SELECT * FROM pages WHERE id=%d LIMIT 1", $getpage);
$result = $con->query($sql);
if ($result && $result->mum_rows > 0 ){
// if page id exists in "pages" table, then make $p = $_GET['p'].
$p = $getpage;
}
else
{
// if "p" ID doesn't exist in DB, then show "unknown page" page with id of "1".
$p = '1';
}
}
else if (!isset ($_GET['p']))
{
//if variable "p" isn't set in link then display homepage or page with ID of 0.
$p = '0';
}
As I commented it's merely about code-formatting and arrangement, here another suggestion that helps a lot when you're doing trouble shooting and is very simple to do:
function has_page_row(Mysqli $db, $pageId)
{
$sql = sprintf("SELECT * FROM pages WHERE id=%d LIMIT 1", $getpage);
$result = $db->query($sql);
return $result && $result->mum_rows > 0;
}
$hasGet = isset($_GET['p']);
$hasRow = $hasGet && has_page_row($con, $_GET['p']);
$p = '0';
if ($hasRow) {
$p = $_GET['p'];
} elseif ($hasGet) {
$p = '1';
}
You can then also easily fix the issue about the dorky SQL query by changing the code inside the new has_page_row function, see:
PHP mysqli query to check if a row exist
i have two types of users on my site, 'free' and 'premium'.
basically i have a messaging system that lists the message and the user who send the message.
when you click on the user's name/image it will link to 'profile.php?id=(user_id)'
what i am trying to do, is if the account type of the user who sent the message = 'free' then i want to take the user to a different link when clicked on.
i am really new to php and am not sure what to do, please can someone show me an example of how i can do this. here's my current code.
function:
function message_account_type() {
global $connection;
global $_SESSION;
global $profile_id;
global $message_id;
$query = "SELECT ptb_users.account_type, ptb_messages.from_user_id
FROM ptb_users, ptb_messages
WHERE ptb_messages.from_user_id = \"$profile_id\"
AND ptb_profiles.user_id = ptb_messages.from_user_id ";
$message_account_type = mysql_query($query, $connection);
confirm_query($query, $connection);
return $message_account_type;
}
php:
<?php
$message_account_type = message_account_type();
while ($type = mysql_fetch_array($message_account_type))
if ($type['account_type'] == 'Premium') {
echo "<?php echo "<a href=\"profile.php?id={$inbox['from_user_id']}\">{$inbox['display_name']}"; ?><? } ?>
<?php
$message_account_type = message_account_type();
while ($type = mysql_fetch_array($message_account_type))
if ($type['account_type'] == 'Free') {
echo "<?php echo "<a href=\"members.php?id={$inbox['from_user_id']}\">{$inbox['display_name']}"; ?><? } ?>
Your best bet is to serve up the relevant template file inside of profile.php. For example, on your profile.php you could do something like this:
$the_user = new User($_REQUEST['id']);
$include_file = ($the_user->account_type == 'free') ? 'free' : 'premium';
include($include_file.'-profile.php');
I seriously have NO IDEA why so many of you open and close <?php tags within a document for no reason...
well a shorter version would be:
<?php
function is_premium_user($profile_id)
{
$query = sprintf("SELECT ptb_users.account_type WHERE ptb_messages.from_user_id = '%s' AND account_type = 'Premium' LIMIT 1", $profile_id );
$result = mysql_query($query);
if (!mysql_fetch_assoc($result))
return false;
return true;
}
$message_account_type = message_account_type();
while ($type = mysql_fetch_array($message_account_type))
if (is_premium_user($profile_id))
echo ' <a href="profile.php?id='.$inbox['from_user_id'].'">'.$inbox['display_name'].'';
else
echo ' <a href="members.php?id='.$inbox['from_user_id'].'">'.$inbox['display_name'].'';
?>
Im trying to come up with MySQL logic for a search function I got on my page. Its a simple form where the user can choose to fill in search criteria. The criteria(s) is send as arguments to a function that generates the mysql logic. This is whats inside the PHP controller file:
case 'search':
if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
&& (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
$members = get_all_username();
} else {
if(isset($_POST['username'])){
$otheruser = $_POST['username'];
} else { $otheruser = null; }
if(isset($_POST['agemin'])){
$ageMin = $_POST['agemin'];
} else { $ageMin = null; }
if(isset($_POST['agemax'])){
$ageMax = $_POST['agemax'];
} else { $ageMax = null; }
if(isset($_POST['country'])){
$country = $_POST['country'];
} else { $country = null; }
//if(isset($_POST['isonline']))
$members = search_members($otheruser, $ageMin, $ageMax, $country);
}
include('displaySearch.php');
break;
So if nothing is set a complete list of all the members is generated and displayed. This is the function that is called if any of the inputs is set:
function search_members($username, $ageMin, $ageMax, $country){
global $db;
$query = "SELECT username FROM profiles WHERE username = :username
AND age > :ageMin AND age < :ageMax AND country = :country";
$statement = $db->prepare($query);
$statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
$statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
$statement->execute();
if($statement->rowCount() >= 1){
return $statement->fetchAll();
} else {
return false;
}
}
The mysql logic is obviously wrong. I need a set of conditions (in the MySQL logic if possible) that checks the PHP variables for value and if there is none it should not be accounted for when querying the database. So if only the username is set in the form the other variables should not be included in the SQL logic.
I've looked up the MySQL IF() condition but Im still not able to come up with proper code that does what I need. If someone could point me in the right direction I would be able to do the rest myself. Any other approach for solving this kind of problem is also welcome.
If i understand your problem, then the simple way is to use if else to build sql query, for example
$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
$sql .= " AND username = :username ";
}
// All other checks
I'm still learning more interesting details about PHP. Example: Moving from MySQL to MySQLi. What I am currently doing is trying enter something like this: http://music.daum.net/artist/main?artist_id=2289
From what I learned from pagination by dicing the url:
main?
artist_id=
2289
How can I be able to make a page like that? I have 2 sections available and will make the others when figuring this out.
artist information (available as testhub-artist.php)
album (available as testhub-artistalbum.php)
music video
photo section
I want to make it easier when making pages instead of making separate folders for each person.
My url would be: "../artist/detail?artist_id=#"
This is at the top of the artist page.
<?php
//Connect to ...
include "testhub-artist.php";
include "testhub-artistalbum.php";
?>
testhub-artist.php
<?php
//Connect to database
include "mysqli_connect.php";
// Construct our join query
$sql = "SELECT * FROM individuals WHERE soloID = 1";
// Create results
$result = mysqli_query($link, $sql);
// Checking if query is successful
if($result){
// Print out the contents of each row into a table
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
// If else states on each variable
if ($profilepic = $row['profilepic']){
$profilepic = $row['profilepic'];
}else{
$profilepic = "DamjuNoImage";
}
if ($engname = $row['engname']){
$engname = $row['engname'];
}else{
$engname = "Unknown";
}
if ($korname = $row['korname']){
$korname = $row['korname'];
}else{
$korname = "Unknown";
}
if ($engbn = $row['engbn']){
$engbn = $row['engbn'];
}else{
$engbn = "Unknown";
}
if ($korbn = $row['korbn']){
$korbn = $row['korbn'];
}else{
$korbn = "Unknown";
}
if ($dateofbirth = $row['dateofbirth']){
$dateofbirth = $row['dateofbirth'];
}else{
$dateofbirth = "Unknown";
}
if ($occupation = $row['occupation']){
$occupation = $row['occupation'];
}else{
$occupation = "Unknown";
}
if ($debut = $row['debut']){
$debut = $row['debut'];
}else{
$debut = "Unknown";
}
if ($recordlabel = $row['recordlabel']){
$recordlabel = $row['recordlabel'];
}else{
$recordlabel = "Unknown";
}
if ($officialsite = $row['officialsite']){
$officialsite = $row['officialsite'];
}else{
$officialsite = "#";
}
if ($sitename = $row['sitename']){
$sitename = $row['sitename'];
}else{
$sitename = "Unknown";
}
} // End of while statement
}else{
$engname = "Unknown";
$korname = "Unknown";
$engbn = "Unknown";
$korbn = "Unknown";
$dateofbirth = "Unknown";
$occupation = "Unknown";
$debut = "Unknown";
$recordlabel = "Unknown";
$officialsite = "#";
$sitename = "Unknown";
} // End of If statement
// Free result set
//mysqli_free_result($result);
?>
testhub-artistalbum.php
<?php
//connect to db
include "mysqli_connect.php";
//check for a page number. If not, set it to page 1
if (!(isset($_GET['albumpage']))){
$albumpage = 1;
}else{
$albumpage = $_GET['albumpage'];
}
//query for record count to setup pagination
$sqli = "SELECT * FROM albums WHERE soloID = 3";
$album_data = mysqli_query($link, $sqli);
$album_rows = mysqli_num_rows($album_data);
//number of photos per page
$album_pagerows = 4;
//get the last page number
$last_album = ceil($album_rows/$album_pagerows);
//make sure the page number isn't below one, or more than last page num
if ($albumpage < 1){
$albumpage = 1;
}elseif ($albumpage > $last_album){
$albumpage = $last_album;
}
//Set the range to display in query
$max_album = 'limit ' .($albumpage - 1) * $album_pagerows .',' .$album_pagerows;
//get all of the photos
$albumList = "";
$sqli2 = "SELECT * FROM albums WHERE soloID = 3 ORDER BY releasedate DESC $max_album";
$album_sql = mysqli_query($link, $sqli2);
//check for photos
$albumCount = mysqli_num_rows($album_sql);
if ($albumCount > 0){
while($album_rows = mysqli_fetch_array($album_sql)){
$albumID = $album_rows["albumID"];
$albumpic = $album_rows["albumpic"];
$title = $album_rows["albumTitle"];
$releasedate = $album_rows["releasedate"];
$page = $album_rows["page"];
$albumList .= '
<li class="albumthumb">
<img class="profile" src="../albums/album_th/' . $albumpic . '.jpg" alt="' . $albumpic . '" width="120" height="120" border="0" /><p class="datatitle">' . $title . '</p><p class="data-releasedate">' . $releasedate . '</p>
</li>
';
}
}else{
$albumList = "There are no available albums at this time!";
}
//mysql_close();
?>
Sorry for not explaining clearly. I want to be able to use pagination when making a profile page like the url. I want to use the number in the url to change the id (soloID) in the sql code.
Good idea in saving time, right? MySQLi getting easier every time I see it.
Thank you.
Changed 5/31/2012 5:44PM CT
$artist = $_GET['artist_id']
into
if(is_numeric($_GET['artist_id'])){
$artist = $_GET['artist_id'];
}else{
$artist = 1;
}
artist/detail?artist_id=#
You would use detail as the page, (probably have a detail folder with a index) and on the detail page, have a $_GET[] variable somewhere that gets the artist_id. So your code could look something like this:
$artist = $_GET['artist_id']; // Filter this variable
$sql = "SELECT * FROM individuals WHERE soloID = '{$artist}'";
/**
* Verify if the ID exists
* Display query results, etc.
*/
So everytime you change the artist_id variable in the URL, the page should change accordingly.
Welcome to my second favorite language! I love php.
Someone already answered your question, but I have some suggestions.
The code you have isn't vulnerable as is cause the user provided data is passed through math... but inlining variables is a good way to leave yourself open to SQL Injection attacks. Look up bind_param() and prepared statements and get in the habit of using them. Always. Well almost always..
Unfortunately SQL doesn't allow you to bind things like the values you use for LIMIT,ORDER BY,GROUP BY so you have to handle those yourself.
Never trust anything derived from a user, so do the work and check it.
Sort columns should always be column names. Check them.
if ( ! in_array($sort_column,array('column1','column2','column3') ) ) $sort_column = 'column1';
Limits should always be integers. Cast them as such.
$safe_limit = (int) $user_limit;
There is no need to copy the array values into another variable. Just use them directly.
You need to escape your values going into html. Lookup urlencode() and htmlentities().
My IE is up to a gig of memory so I'll have to finish this up later.