PHP - How To Display User Profile Image
Good Day PHP world,
I am encountering a problem in php code meant to allow the user to update their profile picture.
I am using jquery.min and jquery.js. The code below runs with no errors reported. The file has been successfully uploaded to upload path using this form.
upload.php
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'> <input type="file" name="photoimg" id="photoimg" class="stylesmall"/> </form>ajaximage.php $path = "uploads/"; $valid_formats = array("jpg", "png", "gif", "bmp","jpeg"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats)) { if($size<(1024*1024)) // Image size max 1 MB { $actual_image_name = $name.".".$ext; $tmp = $_FILES['photoimg']['tmp_name']; if(move_uploaded_file($tmp, $path.$actual_image_name)) { $query = "UPDATE users SET profile_image='$actual_image_name' WHERE student_id='{$_SESSION['user_id']}'"; $result = mysqli_query($link_id, $query); echo "<img src='uploads/".$actual_image_name."' class='preview'>"; }The problem is the image being uploaded does not display on the Student_home.php <div id="about-img"> <img class="profile-photo" align="middle" src='uploads/".$actual_image_name."' /> </div>But the image uploaded will display when i write directly its filename example <div id="about-img"> <img class="profile-photo" align="middle" src="uploads/107.jpg" /> </div>My problem is i wanted to display the uploaded picture of the specific student on Student_Home.php Similar TutorialsHi guys, I am trying to put together a little system that allows users to log onto my website and access there own personal page. I am creating each page myself and uploading content specific to them which cannot be viewed by anyone else. I have got the system to work up as far as: 1/ The user logs in 2/ Once logged in they are re-directed to their own page using 'theirusername.php' Thats all good and working how I need it too. The problem I have is this. If I log onto the website using USER A details - I get taken to USER A's page like I should but - If I then go to my browser and type in USERBdetails.php I can then access USER B's page. This cannot happen!! I need for USER A not to be able to access USER B profile - there is obviously no point in the login otherwise! If you are not logged in you obviously cannot access any secure page. That much is working! Please find below the code I am using: LOGIN <?php session_start(); function dbconnect() { $link = mysql_connect("localhost", "username", "password") or die ("Error: ".mysql_error()); } ?> <?php if(isset($_SESSION['loggedin'])) { header("Location:" . strtolower($username) . ".php"); if(isset($_POST['submit'])) { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $mysql = mysql_query("SELECT * FROM clients WHERE username = '{$username}' AND password = '{$password}'"); if(mysql_num_rows($mysql) < 1) { die("Password or Username incorrect! Please <a href='login.php'>click here</a> to try again"); } $_SESSION['loggedin'] = "YES"; $_SESSION['username'] = $username; $_SESSION['name'] header("Location:" . strtolower($username) . ".php"); } ?> HEADER ON EACH PHP PAGE <?php session_start(); if(!isset($_SESSION['loggedin'])) { die(Access to this page is restricted without a valid username and password); ?> --------------------------------------------------- Am I right in thinking it is something to do with the "loggedin" part? The system I have here is adapted from a normal login system I have been using for years. The original just checks the details and then does a 'session start'. This one obviously has to re-direct to a user specific page. To do this I used the <<header("Location:" . strtolower($username) . ".php");>> line to redirect to a page such as "usera.php" or "userb.php" Any help would be greatly appreciated! Ta Hello all, i require some assistance in a bit of PHP/MySql code. I have a website setup with register/login scripts already wrote, i also have a basic members page for now, that has there user ID assigned to it for example members.php?id=$id, which is there ID from the database. I have a members list which shows all members with links to there profiles, now i when i mouse over the link, it will says members.php?id=1 and so on, which is correct but when clicking on any of the members to go to there profile it is my own details that is shown on there profile instead of theres. members.php <?php session_start(); mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("hireacoder") or die(mysql_error()); $user = $SESSION['username']; $sql = mysql_query("SELECT * FROM users WHERE username='$user'"); $row = mysql_fetch_assoc($sql); echo $row['username']; echo'<br>'; echo $row['fname']; echo'<br>'; echo $row['lname']; echo'<a href="users.php">Users</a>'; ?> users.php <?php session_start(); mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("hireacoder") or die(mysql_error()); echo "<table border='0'> <tr> <th>UserName</th> </tr>"; $sql = mysql_query("SELECT * FROM users ORDER BY ID"); while($row = mysql_fetch_assoc($sql)) { $id = $row['id']; $username = $row['username']; echo" <tr> <td> <a href='members.php?id=$id'>".$username."</a> </td> </tr>"; } echo "</table>"; ?> Now i know what the problem is, the query is getting the details from the DB with the username = the session user which is me and that is why my details show up on all profiles, but i dont know any other way to do it, any help with be very apprciated thanks you. Hi, I recently implemented a code to display user profile information. Well, it displays the username and password fine, but the edit function doesn't seem to be working. I edit the information, click submit, get a success message but the username and password didn't change. myprofile.php Code: [Select] <?php session_start(); include('config.php'); $sql = mysql_query( "SELECT * FROM users WHERE id='".$_SESSION['id']."'" ); echo "<h2>Profile</h2> <form method='post' action='editprofile.php'> <table>"; $row = mysql_fetch_array($sql); echo "<tr><th>Name: </th><td>".$row['username']."</td></tr> <tr><th>Password: </th><td><input type='password' value='".$row['password']."' disabled='true' /></td></tr>"; echo "</table><br /> <input type='submit' value='edit profile' /> </form>"; ?> editprofile.php Code: [Select] <?php include('config.php'); if(isset($_POST['btnedit'])){ $username = $_POST['username']; $password = $_POST['password']; $sql = mysql_query( "UPDATE users SET username='".$username."', password='".$password."' WHERE id='".$_SESSION['id']."'" ); if($sql){ echo "<script>alert('profile updated');window.location='myprofile.php'</script>"; }else{ echo "<script>alert('updating profile failed!');</script>"; } } $sql = mysql_query( "SELECT * FROM users WHERE id='".$_SESSION['id']."'" ); $row = mysql_fetch_array($sql); echo "<h2>Edit profile</h2> <form method='post'> <table> <tr><th>registered:</th><td><input type='text' name='username' value='".$row['username']."'/></td></tr> <tr><th>password:</th><td><input type='password' name='password' value='".$row['password']."'/></td></tr> </table><br /> <input type='submit' name='btnedit' value='update' /> </form>"; ?> Hi, I have to ask about profile page for each user like facebook and netlog. As u can see in netlog it is like this http://en.netlog.com/ElegantLeo and i have a site http://cyprussaver.com/merchant.php?id=64 and here each merchant profile can be viewed like this but i need to show them like this http://cyprussaver.com/rocksman please guide me what i have to do in order to achieve this result. Thanks, Hanan ALi Right ive got a user profile that i want a add friend button but i coded a little something what i fort wud work but no luck <?php session_start(); include "includes/db_connect.php"; include "includes/functions.php"; include"includes/smile.php"; logincheck(); $username=$_SESSION['username']; $viewuser=$_GET['viewuser']; $fetch=mysql_fetch_object(mysql_query("SELECT * FROM users WHERE username='$viewuser'")); if (!$fetch){ echo "No such user"; $totalf = mysql_num_rows(mysql_query("SELECT * FROM friends WHERE username = '$viewuser' AND active='1'")); $invite_text="<div>$username Has Sent You A Friend Request<br> <input name=Yes_Accept type=submit id=yes value=Accept Invite class=abutton> <input name=No_accept type=submit value=Decline Invite class=abutton></div><input type=hidden name=invite_id value=$bar2>"; if (($_GET['fri'])){ $exicst=mysql_query("SELECT * FROM users WHERE username='$viewuser'"); $nums=mysql_num_rows($exicst); $adding=mysql_fetch_object($exicst); $already=mysql_num_rows(mysql_query("SELECT * FROM friends WHERE type='Friend' AND person='$viewuser' AND username='$username'")); if ($already != "0"){ echo "<center><font color=orange><b><br>This user is already your friend.<br><br></font>"; }elseif ($already == "0"){ mysql_query("INSERT INTO `friends` ( `id` , `username` , `person` , `type` , `active`) VALUES ( '', '$username', '$viewuser', 'Friend' , '0' )"); mysql_query("INSERT INTO `friends` ( `id` , `username` , `person` , `type` , `active`) VALUES ( '', '$viewuser', '$username', 'Friend' , '0' )"); mysql_query("INSERT INTO `inbox` ( `id` , `to` , `from` , `message` , `subject` , `date` , `read`) VALUES ( '', '$viewuser', '$username', '$invite_text' , 'Friend Request' , '$date' , '0' )"); $bar2=mysql_insert_id(); echo "<center><font color=orange><br>Your Friend Invitation Was Sent To $viewuser<br><br></font>"; exit(); } }} ?> <a href=?fri=Yes>Add Friend +</a> It just adds a blank person and comes back with No Such User and Your Friend Invitation Was Sent To I think ive put some things in the wrong place to be honest but as im not a pro i easily miss things Hi All, I am currently struggling with the my user info function which is supposed to display an image on my profile page along with the following parts of information taken from my database. The error is a mysql error stating that the $info = mysql_fetch_assoc($result); is not a valid arguement. Code: [Select] function fetch_user_info($uid) { $uid=(int)$uid; $sql = "SELECT `user_id AS `id` `user_username` AS `username`, `user_firstname` AS `firstname`, `user_lastname` AS `lastname`, `user_email` AS `email`, `user_location` AS `location`, `user_about` AS `about`, `user_gender` AS `gender` FROM `users` WHERE `user_id` = {$uid}"; $result = mysql_query($sql); $info = mysql_fetch_assoc($result); $info['avatar'] = "core/user_avatars/{$info['id']}.jpg"; return $info; } I have looked through the code a few times, but I can tell what is wrong. I have included below the profile page code in case it may be an issue there. Code: [Select] <?php include('core/init.inc.php'); $userinfo = fetch_user_info($_GET['uid']); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo $userinfo ['username']; ?>'s Profile</title> </head> <body> <div> <?php if($userinfo == false) { echo 'Sorry, the user does not exist.'; } else { ?> <h1><?php echo $userinfo ['firstname']; ?> <?php echo $userinfo ['lastname']; ?></h1> <img src="<?php echo $userinfo['avatar'];?>" alt="avatar"/> <p>Username: <?php echo $userinfo ['username']; ?></p> <p>First Name: <?php echo $userinfo ['firstname']; ?></p> <p>Last Name: <?php echo $userinfo ['lastname']; ?></p> <p>Gender: <?php echo ($userinfo ['gender'] == 1) ? 'Male' : 'Female'; ?></p> <p>Email: <?php echo $userinfo ['email']; ?></p> <p>Location: <?php echo $userinfo ['location']; ?></p> <p>About: <?php echo $userinfo ['about']; ?></p> </div> <?php } ?> </body> </html> Thanks Jamie I am trying to upload files to a user profile system. here is the profile page Code: [Select] <?php include('core/init.inc.php'); if (isset($_POST['email'], $_POST['location'], $_POST['about'])) { $errors = array(); if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = "The email address you entered is not valid"; } if(preg_match('#^[a-z0-9 ]+$#i',$_POST['location'])===0) { $errors[] = 'Your location must only contain A-Z 0-9 and spaces.'; } if (empty($_FILES['avatar']['tmp_name']) === false) { $file_ext = end(explode('.', $_FILES['avatar']['name'])); if(in_array(strtolower($file_ext), array('jpg', 'jpeg', 'gif', 'png')) === false) { $errors[] = 'Your avatar must be an image.'; } } if(empty($errors)) { print_r($_FILES); set_profile_info($_POST['email'],$_POST['location'],$_POST['about'], (empty($_FILES['avatar']['tmp_name'])) ? false : $_FILES['avatar']['tmp_name']); } $userinfo = array( 'email' => htmlentities($_POST['email']), 'location' => htmlentities($_POST['location']), 'about' => htmlentities($_POST['about']) ); } else { $userinfo = fetch_user_info($_SESSION['uid']); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Edit your Profile</title> </head> <body> <div> <?php if(isset($errors) == false) { echo 'Click update to edit your profile.'; } else if(empty($errors)) { echo 'Your profile has been updated.'; } else { echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>'; } ?> </div> <form action="" method="post" enctype="multipart/form-data"> <div> <label for="email">Email: </label> <input type="text" name="email" id="email" value="<?php echo $userinfo['email']; ?>" /> </div> <div> <label for="location">Location: </label> <input type="text" name="location" id="location" value="<?php echo $userinfo['location']; ?>" /> </div> <div> <label for="about">About Me: </label> <textarea name="about" id="about" rows="14" cols="50"><?php echo strip_tags($userinfo['about']); ?></textarea> </div> <div> <label for="avatar">Avatar: </label> <input type="file" name="avatar" id="avatar"/> </div> <div> <input type="submit" value="Update" /> </div> </form> </body> </html> here is the function taken from an external file Code: [Select] function set_profile_info($email, $location,$about,$avatar) { $email = mysql_escape_string(htmlentities($email)); $about = mysql_escape_string(nl2br(htmlentities($about))); $location = mysql_escape_string($location); if (file_exists($avatar)) { $src_size = getimagesize($avatar); if ($src_size['mime'] === 'image/jpeg') { $src_img = imagecreatefromjpeg($avatar); } else if ($src_size['mime'] === 'image/png') { $src_img = imagecreatefrompng($avatar); } else if ($src_size['mime'] === 'image/gif') { $src_img = imagecreatefromgif($avatar); } else { $src_img = false; } if ($src_img !== false) { $thumb_width= 200; if($src_size[0] <= $thumb_width) { $thumb = $src_img; } else { $new_size[0] = $thumb_width; $new_size[1] = ($src_size[1] / $src_size[0]) * $thumb_width; $thumb = imagecreatetruecolor($new_size[0], $new_size[1]); imagecopyresampled($thumb, $src_img, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]); } imagejpeg($thumb, "{$GLOBALS['path']}/user_avatars/{$_SESSION['uid']}.jpg"); } } $sql = "UPDATE `users` SET `user_email` = '{$email}', `user_about` = '{$about}', `user_location` = '{$location}' WHERE `user_id` = {$_SESSION['uid']}"; mysql_query($sql); } Below I have returned the array of files to check if its been uploaded correctly. Array ( [avatar] => Array ( [name] => Sonic.jpg [type] => image/jpeg [tmp_name] => /var/tmp/php.waq8n [error] => 0 [size] => 48477 ) ) But I get this error message. Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '/var/tmp/php.waq8n' is not a valid JPEG file in /web/stud/u0963643/userprofilesection/finaluserprofile/core/inc/user.inc.php on line 71 If someone could point out where in this code I have made an error I would be very grateful Thanks Jamie Hi, I am making a dating site where I have made the user profile edit page visible to the user when they log in, and I think I can get away with not showing the user their "public" profile view. But I definitely need to show other users on the site the "public" non editing profile page view. But I don't know how to do this. I have yet to create the search, search results, thumbnails with optional descriptions of the possible dating results. But I first want to just get 2 versions of the user profile page view. One that the user sees that I have already done. (The editable one). And the other I need to make which is the page the other users will see, (The public profile) Please if anyone has any idea how to do this I would greatly appreciate it, especially if you have any pseudocode ideas. thank you. Hello users: I am exploring the delightful world of PHP for web applications. I am in the stage where I need to use SESSIONS and COOKIES and MYSQL for a user/membership/profile structure. I understand most of the grammar behind PHP and am excited to apply this in application. I am searching for recommendations and comments about using: 1. COOKIES 2. SESSIONS 3. MYSQL/SQL Almost every website has an authentication mechanism, profile, and use information. My website required this similar structure, but I have been having some problems completing all of the technical steps for production. If anyone has code samples or places where I can review code on this topic, that would be wonderful. I am specifically searching for more advanced topics in these area for general robustness. Please kindly send me a message or respond to this post. Regards, Diamond Edited by Diamond, 30 December 2014 - 04:27 PM. Hi all, I am currently facing a problem, if you look at 'viewprofile.jpg' attachment, you can see that there is an uploaded profile picture. However when I click to edit the profile, the picture is missing (editprofile.jpg), I am just wondering what went wrong? Can someone guide me in troubleshooting this problem? Code: [Select] <?php if (isset($_POST['submit'])) { // Validate and move the uploaded picture file, if necessary if (!empty($new_picture)) { if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') || ($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= CT_MAXFILESIZE)) { //0 indicates a success, other values indicate failure if ($_FILES['file']['error'] == 0) { // Move the file to the target upload folder $target = CT_UPLOADPATH . basename($new_picture); if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) { // The new picture file move was successful, now make sure any old picture is deleted if (!empty($old_picture) && ($old_picture != $new_picture)) { @unlink(CT_UPLOADPATH . $old_picture); } } else { // The new picture file move failed, so delete the temporary file and set the error flag @unlink($_FILES['new_picture']['tmp_name']); $error = true; echo '<p class="error">Sorry, there was a problem uploading your picture.</p>'; } } } else { // The new picture file is not valid, so delete the temporary file and set the error flag @unlink($_FILES['new_picture']['tmp_name']); $error = true; echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (CT_MAXFILESIZE / 1024). '</p>'; } } // Grab the profile data from the POST $name = mysqli_real_escape_string($dbc, trim($_POST['name'])); $nric = mysqli_real_escape_string($dbc, trim($_POST['nric'])); $gender = mysqli_real_escape_string($dbc, trim($_POST['gender'])); $old_picture = mysqli_real_escape_string($dbc, trim($_POST['old_picture'])); $new_picture = mysqli_real_escape_string($dbc, trim($_FILES['new_picture']['name'])); $new_picture_type = $_FILES['new_picture']['type']; $new_picture_size = $_FILES['new_picture']['size']; list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']); $error = false; // Update the profile data in the database if (!$error) { if (!empty($name) && !empty($nric) && !empty($gender)) { $query = "UPDATE tutor_profile SET name = '$name', nric = '$nric', gender = '$gender' WHERE tutor_id = '" . $_GET['tutor_id'] . "'"; mysqli_query($dbc, $query) or die(mysqli_error($dbc)); // Confirm success with the user echo '<p>Your profile has been successfully updated. Would you like to <a href="viewprofile.php?tutor_id=' . $_GET['tutor_id'] . '">view your profile</a>?</p>'; mysqli_close($dbc); exit(); } else { echo '<p class="error">You must enter all of the profile data (the picture is optional).</p>'; } } } // End of check for form submission else { // Grab the profile data from the database $query = "SELECT name, nric, gender FROM tutor_profile WHERE tutor_id = '" . $_GET['tutor_id'] . "'"; $data = mysqli_query($dbc, $query) or die(mysqli_error($dbc)); // The user row was found so display the user data if (mysqli_num_rows($data) == 1) { $row = mysqli_fetch_array($data); if ($row != NULL) { $name = $row['name']; $nric = $row['nric']; $gender = $row['gender']; } else { echo '<p class="error">There was a problem accessing your profile.</p>'; } } } mysqli_close($dbc); ?> <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo CT_MAXFILESIZE; ?>" /> <ul id="tabSet_ep"> <li><a href="#panel1">Personal Profile</a></li> <li><a href="#panel2">Qualifications</a></li> <li><a href="#panel3">Tutor\'s Comments/Commitment</a></li> <li><a href="#panel4">Tutoring Levels/Subjects</a></li> </ul> <!--Personal Profile--> <div id="panel1"> <label for="new_picture">Pictu </label> <input type="file" id="new_picture" name="new_picture" /> <?php if (!empty($old_picture)) { echo '<img class="profile" src="' . CT_UPLOADPATH . $old_picture . '" alt="Profile Picture" />'; } ?><br /> <label for="firstname">First name:</label> <input type="text" id="firstname" name="firstname" value="<?php if (!empty($name)) echo $name; ?>" /><br /> <label for="lastname">Last name:</label> <input type="text" id="lastname" name="lastname" value="<?php if (!empty($nric)) echo $nric; ?>" /><br /> <label for="gender">Gender:</label> <select id="gender" name="gender"> <option value="M" <?php if (!empty($gender) && $gender == 'M') echo 'selected = "selected"'; ?>>Male</option> <option value="F" <?php if (!empty($gender) && $gender == 'F') echo 'selected = "selected"'; ?>>Female</option> </select><br /> </div> <input type="submit" value="Save Profile" name="submit" /> </form> hi, i have made a website where people resgister their details of them and products. they have to enter the following details in form Name of company name of the product company address email id password mobile number contact and brief details about their company
user can then login with email id and pwd. now after login ..user will get a page where he can upload the photos of products images and their price, so now my question is that when he finishes uploading (|by clicking on upload button) the product images and price text box ..then on final uploaded webspage it should show all other things which he registerd before (company name , mobile number etc) along with images and price...hence the main question that user does not need to enter mobile and address while uploading images and filling proce ..but on the final page it should show mobile and address along with price and images..as user is not going to enter mobile and address again and again as he will have multiple products to upload.
Hello, currently, I got myself a site where you have your own profile and your own 'profile image'. I allow people to upload their own image, and checking my folder, it indeed uploads it correctly. Now the issue starts when you try to delete your image, again - when deleted the image is deleted in the folder.. However, when then uploading a NEW image, it simply displays the old one (While the new one is actually in the folder!?) I figured that if you would close the website, and then load it again - it works correctly (figured this means the old image is still loaded in your temp files or something?) Now I was wondering if you could actually somehow *force* the user to re-download this image when you upload a new one. Thanks for your time! This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=342583.0 I want to fetch data from a table let's say table "activities". Uid | day | activity | time | remarks 1. Mon. Act1. 3pm. Good 2. Mon. Act1. 5pm. Bad 1. Tue. Act2. 12am. Bad 1. Tue. Act5. 1am. Bad 1. Thur. Act8. 9pm. Good 2. Wed. Act4. 7am. Good
Now assuming I want to fetch all the data that is related to user Id 1 and display them in another table (Uid 1). Which is 4 rows according to the table, how do I go about it using select query? Thanks!!! I tried something like this but it displays just one row <?php $uid = $_SESSION['login']; $sql2 = "SELECT * FROM Activities WHERE uid=? ORDER BY Uid LIMIT 6"; $stmt2 = $connection->prepare($sql2); $stmt2->bind_param('i', $Uid); $stmt2->execute(); $result2 = $stmt2->get_result(); $row2 = $result2->fetch_assoc(); //now am stuck here ?> now trying to display the fetch those data for only Uid 1 in these simple format...
<table style="width:100%"> <tr> <th>Day</th> <th>Activity</th> <th>Remarks</th> </tr> <tr> <td>Mon</td> <td>Act1</td> <td>Good</td> </tr> <tr> <td>Tue</td> <td>Act2</td> <td>Bad</td> </tr> <tr> <td>Tue</td> <td>Act5</td> <td>Bad</td> </tr> </table>
Dear everyone, I am reasonably new to php, so there is a chance that what I am asking for may exceed my grasp. Nevertheless I'd like to try: Is it possible to let the user choose (by using a drop down listbox for instance) which table from a database to display on a page? And/or which database to display on a page? Background information: I'm working on a website for my chess club. I've already got a working page (html,css) with a table of the standings (mysql, php) of the latest round (with position number, name, points, wins, losses, etc). By clicking on the column header, it sorts the respective column. What I'd finally like to do is let the user choose to display a different round (table), or even a different season (database). I could make a seperate page for each round, but I'd like to know if there's a more elegant way to do this by using only one page and one or more databases. Thanks in advance for any tips and best wishes from The Netherlands, Wouter. after the user has logged in, I would like to display their details by barcode id Login.php <?php $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name=""; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); session_start(); // username and password sent from form $barcodeID=$_POST['barcode']; // To protect MySQL injection (more detail about MySQL injection) $barcodeID = stripslashes($barcodeID); $barcodeID = mysql_real_escape_string($barcodeID); $sql="SELECT * FROM $tbl_name WHERE BarcodeID='$barcodeID'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count > 0){ $data = mysql_fetch_array ($result); $_SESSION["user_id"] = $data["BarcodeID"]; $_SESSION["user_firstname"] = $data["Firstname"]; $_SESSION["user_surname"] = $data["Surname"]; $_SESSION["user_jobrole"] = $data["JobRole"]; $_SESSION["user_manager"] = $data["Manager"]; $_SESSION["user_priority"] = $data["Priority"]; $_SESSION["user_datejoined"] = $data["DateJoined"]; $_SESSION["user_times_loggged_in"] = $data["TimesLoggedOn"]; if ($_SESSION["user_priority"] == '1') { header("Location: AdminSection.php"); } else { header("Location:LoggedIn.php"); } if ($_SESSION["user_times_loggged_in"] == '0') { header("Location:UsingTheSystem.html"); } } ?> LoggedIn.php I keep getting the error undefined index "barcode"? <?php $barcodeID = $_POST["barcode"]; include 'dbcon.php'; $sql = "SELECT Firstname, Surname, JobRole, Manager" . " FROM users" . " WHERE BarcodeID = .'$barcodeID'" ; $rows = mysql_query($sql); echo $rows; ?> Any help will be greatly appreciated Thanks Hi, I'm trying to display a user review system allowing user's to vote. This works fine, but I'm trying to user php to only display the rating system if the user is logged in and display alternate text if they are not. I am getting the following error: Parse error: syntax error, unexpected T_ELSE in XXXXXX on line 182 Here's the code: Code: [Select] <?php if ($_SESSION['username']){ $query = mysql_query("SELECT * FROM locations WHERE name = '$location'"); while($row = mysql_fetch_array($query)) { $rating = (int)$row[rating] ?> <div class="floatleft"> <div id="rating_<?php echo $row[id]; ?>"> <span class="star_1"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 0) { echo"class='hover'"; } ?> /></span> <span class="star_2"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 1.5) { echo"class='hover'"; } ?> /></span> <span class="star_3"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 2.5) { echo"class='hover'"; } ?> /></span> <span class="star_4"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 3.5) { echo"class='hover'"; } ?> /></span> <span class="star_5"><img src="fivestars/star_blank.png" alt="" <?php if($rating > 4.5) { echo"class='hover'"; } ?> /></span> </div> </div> <div class="star_rating"> (Rated <strong><?php echo $rating; ?></strong> Stars) </div> <div class="clearleft"> </div> } } <?php else { echo "Log in to review"; } ?> Thanks in advance for any help. I'm sure it's something trivial but I can't see it! Code: [Select] <html> <title>Micro Elite Brigade - Registration</title><LINK REL="SHORTCUT ICON" HREF="images/favicon.png"><?php require_once('upper.php'); require_once('database.php'); echo $error_msg=''; if(isset($_POST['submit'])) { $LoginId=mysqli_real_escape_string($dbc,trim($_POST['LoginId'])); $Password1=mysqli_real_escape_string($dbc,trim($_POST['Password1'])); $Password2=mysqli_real_escape_string($dbc,trim($_POST['Password2'])); $Name=mysqli_real_escape_string($dbc,trim($_POST['Name'])); $Age=mysqli_real_escape_string($dbc,trim($_POST['Age'])); $BloodGroup=mysqli_real_escape_string($dbc,trim($_POST['BloodGroup'])); /*if(!isset($_POST['Sex'])) { echo 'Please enter Sex<br>'; }*/ //else{ $Sex= mysqli_real_escape_string($dbc,trim($_POST['Sex'])); //} $Qualification=mysqli_real_escape_string($dbc,trim($_POST['Qualification'])); $ContactNumber=mysqli_real_escape_string($dbc,trim($_POST['ContactNumber'])); $Email=mysqli_real_escape_string($dbc,trim($_POST['Email'])); $Address=mysqli_real_escape_string($dbc,trim($_POST['Address'])); $AboutYourself=mysqli_real_escape_string($dbc,trim($_POST['AboutYourself'])); //$countCheck=count($_POST['checkbox']); //echo $countCheck; //$checkbox=$_POST['checkbox']; //$countCheck=count($checkbox); if(empty($LoginId)){echo 'Please enter Login Id';} elseif(empty($Password1)){echo 'Please enter Password';} elseif(empty($Password2)){echo 'Please confirm Password';} elseif($Password1!==$Password2){echo 'Password didn\'t match';} elseif(empty($Name)){echo 'Please enter Name';} elseif(empty($Age)){echo 'Please enter Age';} elseif(!isset($_POST['Sex'])){echo 'Please enter Sex';} elseif(empty($Qualification)){echo 'Please enter Qualification';} elseif(empty($ContactNumber)){echo 'Please enter Contact Number';} elseif(empty($Email)){echo 'Please enter Email';} elseif(empty($Address)){echo 'Please enter Address';} elseif(empty($AboutYourself)){echo 'Please enter About Yourself';} elseif(!isset($_POST['checkbox'])){ echo 'You have to register at least one activity.';} elseif(!isset($_POST['TermsAndConditions'])){ echo 'You have to agree all Terms and Conditions of Elite Brigade.';} else { require_once('database.php'); $query="select * from registration where LoginId='$LoginId'"; $result=mysqli_query($dbc,$query); if(mysqli_num_rows($result)==0) { $checkbox=$_POST['checkbox']; $countCheck=count($_POST['checkbox']); $reg_id=' '; for($i=0;$i<$countCheck;$i++) { $reg_id=$reg_id.$checkbox[$i].','; $query="insert into activity_participation (LoginId,Title,Date) values ('$LoginId','$checkbox[$i]',CURDATE())"; $result=mysqli_query($dbc,$query) or die("Not Connected"); } $query="insert into registration (LoginId,Password,Name,Age,BloodGroup,Sex,Qualification,ContactNumber,Email,Address,AboutYourself,Activity)values ('$LoginId',SHA('$Password1'),'$Name','$Age','$BloodGroup','$Sex','$Qualification','$ContactNumber','$Email','$Address','$AboutYourself',',$reg_id')"; $result=mysqli_query($dbc,$query) or die("Not Connect"); echo ' Dear '.$Name.'.<br>Your request has been mailed to admin.<br>Your account is waiting for approval<br>'; $from= 'Elite Brigade'; $to='ankitp@rsquareonline.com'; $subject='New User Registration'; $message="Dear admin,\n\nA new user request for registration. Please check it out.\n\nRegards\nMicro"; mail($to,$subject,$message,'From:'.$from); //header('Location: index.php'); // header('Location: Registration.php'); } else { echo 'Dear '.$Name. ', <br> An account already exist with login-id<b> '.$LoginId.'</b> <br>Please try another login-id'; }} } ?> <html> <head> <link rel="stylesheet" type="text/css" href="css/style.css" /> <script type="text/javascript"> function lengthRestriction(elem, min, max){ var uInput = elem.value; if(uInput.length >= min && uInput.length <= max){ return true; }else{ alert("Please enter between " +min+ " and " +max+ " characters"); elem.value=""; return false; } } function emailValidator(elem, helperMsg){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.value=""; return false; } } </script> </head> <body> <?php echo $error_msg; ?> <form action='<?php echo $_SERVER['PHP_SELF'];?>' id="commentForm" method='post'> <div class="registration_and_activity"> <table border="0" cellspacing="0" cellpadding="0" width="380"> <tr><td colspan="2"> <br/><h3>New User?</h3></td></tr> <tr><td width="120"> <em>*</em>Enter Login id</td><td width="150"><input type='text' name='LoginId' id='LoginId' value='<?php if(!empty($LoginId))echo $LoginId;?>' onblur="lengthRestriction(document.getElementById('LoginId'), 6, 20)")/></td></tr> <tr><td> <em>*</em>Enter Password</td> <td><head> <SCRIPT language=Javascript> function capLock(e){ kc = e.keyCode?e.keyCode:e.which; sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false); if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)) { if(document.getElementById('Password1').value=='') alert("Caps Lock is On"); } else document.getElementById('divMayus').style.visibility = 'hidden'; } </SCRIPT> </HEAD> <input onkeypress='return capLock(event)' type='password' name='Password1' id="Password1" value='<?php if(!empty($Password1))echo $Password1;?>' onblur="lengthRestriction(document.getElementById('Password1'), 4, 50)")/></td></tr> <tr><td> <em>*</em>Confirm Password</td><td><input type='password' name='Password2' value='<?php if(!empty($Password2))echo $Password2;?>' /></td></tr> <tr><td width="120"> <em>*</em>Enter Name</td> <td><input type='text' name='Name' Id="Name" value='<?php if(!empty($Name))echo $Name;?>' onblur="lengthRestriction(document.getElementById('Name'), 2, 30)")/></td></tr> <tr><td> <em>*</em>Enter Age</td><HEAD> <SCRIPT language=Javascript> function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } </SCRIPT> </HEAD> <td><INPUT onkeypress='return isNumberKey(event)' type='text' name='Age' value='<?php if(!empty($Age))echo $Age;?>'/></td></tr> <tr><td> <em>*</em>Enter Blood</td><td><input type='text' name='BloodGroup' value='<?php if(!empty($BloodGroup))echo $BloodGroup;?>' id="BloodGroup" onblur="lengthRestriction(document.getElementById('BloodGroup'), 1, 3)") /></td></tr> <tr><td> <em>*</em>Enter Sex</td><td><input type='radio' name='Sex' style='width:16px; border:0;' value='Male'<?php if(isset($_POST['Sex'])) { echo "checked='checked'";} ?> />Male <input type='radio' name='Sex' style='width:16px; border:0;' value='Female' <?php if(isset($_POST['Sex'])) { echo "checked='checked'";} ?> />Female</td></tr> <tr><td> <em>*</em>Enter Qualification</td><td><input type='text' name='Qualification' value='<?php if(!empty($Qualification))echo $Qualification;?>' id="Qualification" onblur="lengthRestriction(document.getElementById('Qualification'), 3, 60)"/></td></tr> <tr><td> <em>*</em>Contact Number </td><td><input onkeypress='return isNumberKey(event)'type='text' name='ContactNumber' value='<?php if(!empty($ContactNumber))echo $ContactNumber;?>' /></td></tr> <tr><td> <em>*</em>Enter Email</td><td><input type='text' name='Email'class="email" value='<?php if(!empty($Email))echo $Email;?>' id="emailer" onblur="emailValidator(document.getElementById('emailer'), 'Not a Valid Email')"/></td></tr> <tr><td> <em>*</em>Enter Address</td><td><input type='text' name='Address' value='<?php if(!empty($Address))echo $Address;?>' id="Address" onblur="lengthRestriction(document.getElementById('Address'), 2, 100)")/></td></tr> <tr ><td > <em>*</em>About Yourself </td></tr> <tr><td colspan="2"><textarea rows='10' cols='40' name='AboutYourself' id="AboutYourself" onblur="lengthRestriction(document.getElementById('AboutYourself'), 5, 500)") /><?php if(!empty($Address))echo $Address;?></textarea></td></tr> <tr><td> <?php echo" <tr><td colspan='2'><em>*</em><b>Select fields for which you want to register</b></td></tr>"; require_once('database.php'); $query="select * from activity"; $result=mysqli_query($dbc,$query); while($row=mysqli_fetch_array($result)){ $Title=$row['Title']; $ActivityId=$row['ActivityId']; echo "<tr><td>$Title</td>"; echo "<td><input type='checkbox' name='checkbox[]' value='$Title' style='width:14px; text-align:right;'/></td></tr>";//value=$ActivityId tells ActivityId variable extracts with name="checkbox" echo "<br/>"; } echo " <tr> <table border='0' cellspacing='0' cellpadding='0' width='400' style='margin:10px 0 0 0;'> <td align='left' valign='top' scope='col' width='80'><em>*</em><input type='checkbox' name='TermsAndConditions' style='width:14px; text-align:right;'/></td> <td align='left' valign='top' scope='col'> I agree all <a href='TermsAndConditions.php'>Terms and conditions </a>of Elite Brigade.</td> </table> </tr>"; echo "<tr><td colspan='2' align='center'><input type='submit' value='Register' name='submit' style='background:url(./images/button_img2.png) no-repeat 10px 0px; width:100px; padding:3px 0 10px 0; color:#FEFBC4; border:0; margin:15px 0 5px 100px; '/></td></tr><br>"; echo " </td></tr></table> </div> </form> </body> </html>"; require_once('lower.php'); ?>Hi friends.......... I have two problems with this page....... 1--> When user not select radio button it should displays "Please enter Sex" but on submit it displays an error "Undefined index: Sex in C:\wamp\www\EliteBrigadeserver\RegistrationAndActivity.php on line 19 Please enter Sex." I want to remove this notice........ 2--> If user not fill any field and press submit then if user once selected his sex, it should remain selected. Help me please............ Anyone????????? thanks in advance................... Hi all I need some help with displaying user account details i am currently able to show only the email address and i would like to show the name school name and yeargroup heres my code for myaccount.php <?php require_once('Connections/isn_1.php'); ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "1,2,3,4"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "login.php?login=false"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) $MM_referrer .= "?" . $_SERVER['QUERY_STRING']; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <!DOCTYPE HTML> <html> <head> <title>My Account - <?php echo($_SESSION['MM_Username']); ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <style type="text/css"> @import url("style.css"); </style> </head> <body class="about"> <!-- Start NavBar --> <div id="topnavbar"> <dl> <dt id="home"><a href="index.php">Home</a></dt> <dt id="about"><a href="about.php">About</a></dt> <dt id="account"><a href="myaccount.php">Account</a></dt> <dt id="login"><a href="login.php">Login</a></dt> </dl> <dl id="rightnavbar"> <dt id="ISN"><a href="index.php">ISN</a></dt> </dl> </div> <!-- End NavBar --> <div id="page-container"> <div id="header"> </div> <div id="sidebar-a"></div> <div id="content"> <div class="padding"> <center> <table width="631" border="0"> <tr> <td colspan="2">Personal Details</td> </tr> <tr> <td width="229"> </td> <td width="648"></td> </tr> <tr> <td>Name</td> <td></td> </tr> <tr> <td>Email</td> <td><?php echo($_SESSION['MM_Username']); ?></td> </tr> <tr> <td>School Name</td> <td></td> </tr> <tr> <td>Year Group</td> <td></td> </tr> <tr> <td>DOB</td> <td></td> </tr> <tr> <td> </td> <td><a href="updateprofile.php">Modify my details</a></td> </tr> </table> <a href="logout.php">Logout?</a> </center> </div> </div> <div id="footer"> <div id="altnav"> <a href="index.php">Home</a> - <a href="login.php">Login</a> - <a href="register.php">Register</a> - <a href="about.php">About</a> - <a href="terms.php">Terms & Conditions</a> </div> <div id="copyright">© 2011 InterSchoolsNetwork, All Rights Reserved - A <a href="http://jordansmithsolutions.co.uk">Jordan Smith Solutions</a> & <a href="http://www.joecocorp.webs.com/">JoeCo Corp Production</a><br /> </div> </div> </div> </body> </html> <?php mysql_free_result($rsUpdateUser); ?> If you need any other code to help answer it for me then let me no please I have a php page that is linked to in a Joomla site in a Wrapper. I want to be able to block access to a php page unless it was called by a link in the main menu. I figured I could use $_SERVER['HTTP_REFERER'] to accomplish this like so: Link from Main Menu -> top_secret.php Code: [Select] <?php //the following is placed in the header of top_secret.php web page $page1 = 'http://myweb.com/index.php?option=com_wrapper&view=wrapper&Itemid=201';//page that user must come from $menu_link = $_SERVER['HTTP_REFERER'];//page that user comes from if($page1 !== $menu_link) { header('Location: http://myweb.com/error_page.php'); } ?> Thus if some one tries to simply access the top_secret.php with out going through the joomla menu- they will be re-directed to an error page. My question to the guru's is- is this secure or can someone easily get to the top_secret.php without going through the menu. Keep in mind- that the menu the person must use is only accessible from a registered joomla user for that site. Hope that makes sense. |