PHP - Reference Stored Image
I am writting a php function that uses mysql to get user data - pretty common, right
Well, my issue is that I need to run a check in my file system. Users profile pictures are stored in my image directory as .png's. I need to have my function check that directory and if an image matches their id, then return their information. I only want the user data if they have an image uploaded. Here is my current function: Code: [Select] function fetch_users_login($limit) { $limit = $limit(int); $sql = "SELECT `users`.`id`, `users`.`firstname`, `users`.`lastname`, `users`.`username`, `user_privacy`.`avatar` FROM `users` LEFT JOIN `user_privacy` ON `users`.`id` = `user_privacy`.`uid` WHERE `users`.`status` > 2 AND `user_privacy`.`avatar` = 1 ORDER BY `users`.`id` DESC LIMIT 0, {$limit}"; $result = mysql_query($sql) or die(mysql_error()); $users = array(); $i = 0; while(($row = mysql_fetch_assoc($result)) !== false) { $users[$i] = array( 'id' => $row['id'], 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], ); $users[$i]['avatar'] = getUserAvatar($row['username']); $i++; } return $users; } Similar TutorialsHi
I am winning I think
I have got the records displayed for the current user logged in so basically they can only see their submitted listings and just working on the edit of them so the current user logged in can update their listing and is all working apart from the update of the images
the images are stored by the file name on the database and then gets moved onto the server so the actual images are not stored on the database only the file names are and the images are moved onto the server, hope that makes sense
what I can't do at the mo is work out how to update the file names of the images on the database and update on the server
I get the following error
Notice: Undefined index: photo on line 209 and line 211
the coding for them lines are below
$pic1= basename($_FILES['photo']['name'][0]); $pic2= basename($_FILES['photo']['name'][1]);The rest of the coding below that is if(!empty($_FILES['photo']['tmp_name'])) { // Number of uploaded files $num_files = count($_FILES['photo']['tmp_name']); /** loop through the array of files ***/ for($i=0; $i < $num_files;$i++) { // check if there is a file in the array if(!is_uploaded_file($_FILES['photo']['tmp_name'][$i])) { $messages[] = 'No file uploaded'; } else { // move the file to the specified dir if(move_uploaded_file($_FILES['photo']['tmp_name'][$i],$target.'/'.$_FILES['photo']['name'][$i])) { $messages[] = $_FILES['photo']['name'][$i].' uploaded'; } else { // an error message $messages[] = 'Uploading '.$_FILES['photo']['name'][$i].' Failed'; } } }The update query is below // save the data to the database mysql_query("UPDATE privatelistings SET listingtitle='$listingtitle', make='$model', model='$model', exteriorcolour='$exteriorcolour', enginesize='$enginesize', fueltype='$fueltype', yearregistered='$yearregistered', transmission='$transmission', mileage='$mileage', nodoors='$nodoors', bodystyle='$bodystyle', price='$price', photo='$pic1', photo1='$pic2' WHERE id='$id'") or die(mysql_error());I am going to be updating to mysqli just want to get it working first My HTML form coding is below <form action="" method="post" enctype="multipart/form-data"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div> <strong>Listing Title: *</strong> <input type="text" name="listingtitle" value="<?php echo $listingtitle; ?>"/> <br/> <strong>Make: *</strong> <input type="text" name="make" value="<?php echo $make; ?>"/> <br/> <strong>Model: *</strong> <input type="text" name="model" value="<?php echo $model; ?>"/> <br/> <strong>Exterior Colour: *</strong> <input type="text" name="exteriorcolour" value="<?php echo $exteriorcolour; ?>"/> <br/> <strong>Engine Size: *</strong> <input type="text" name="enginesize" value="<?php echo $enginesize; ?>"/> <br/> <strong>Fuel Type: *</strong> <input type="text" name="fueltype" value="<?php echo $fueltype; ?>"/> <br/> <strong>Year Registered: *</strong> <input type="text" name="yearregistered" value="<?php echo $yearregistered; ?>"/> <br/> <strong>Transmission: *</strong> <input type="text" name="transmission" value="<?php echo $transmission; ?>"/> <br/> <strong>Mileage: *</strong> <input type="text" name="mileage" value="<?php echo $mileage; ?>"/> <br/> <strong>Number of Doors: *</strong> <input type="text" name="nodoors" value="<?php echo $nodoors; ?>"/> <br/> <strong>Body Style: *</strong> <input type="text" name="bodystyle" value="<?php echo $bodystyle; ?>"/> <br/> <strong>Price: *</strong> <input type="text" name="price" value="<?php echo $price; ?>"/> <br/> <strong>Photo One:</strong> <input type='hidden' name='size' value='350000'><input type='file' name='photo[]'> <br> <strong>Photo Two:</strong> <input type='hidden' name='size' value='350000'><input type='file' name='photo[]'> <br> <input type="submit" name="submit" value="Submit"> </div> </form>sorry was not sure what other I need to show, so you guys get the idea? I put together the following blocs of code for uploading pictures into a database and displaying them on a webpage. The pictures are supposed to be displayed on the member's only page of a website I'm working on, upon logging in, and they are supposed to be the member's uploaded picture. I created several members and and used one of my existing member accounts to test the uploading process. The picture upload process appeared to have been successful when I checked on myphpadmin. Yet, when I login with this account, no picture is displayed, instead, a tiny jpg icon is displayed at the top left corner of the box in which the picture was supposed to be displayed. Same thing when I login with the other accounts with which I haven't yet uploaded a picture. I'll start with the code that installs the table in the database $query = "CREATE TABLE images ( image_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , member_id INT UNSIGNED, like_id INT UNSIGNED, image LONGBLOB NOT NULL, image_name varchar(255) NOT NULL, image_type varchar(4) NOT NULL, image_size int(8) NOT NULL, image_cartegory VARCHAR(20) NOT NULL, image_path VARCHAR(300), image_date DATE )"; Then here is the code which allows the member to upload his pictu <form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer"> <input name="MAX_FILE_SIZE" value="102400" type="hidden"> <input name="image" accept="image/jpeg" type="file"> <input value="Submit" type="submit"> </form> And here is the insertimage.php which inserts the image into our database: Note that I have to authenticate the user in order to register his session id which is used later on in the select query to identify him and select the right image that corresponds to him. <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Make sure the user actually // selected and uploaded a file if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { // Temporary file name stored on the server $tmpName = $_FILES['image']['tmp_name']; // Read the file $fp = fopen($tmpName, 'r'); $data = fread($fp, filesize($tmpName)); $data = addslashes($data); fclose($fp); // Create the query and insert // into our database. $query = "INSERT INTO images (member_id, image_cartegory, image_date, image) VALUES ('{$_SESSION['id']}', 'main', NOW(), '$data')"; $results = mysql_query($query); // Print results print "Thank you, your file has been uploaded."; } else { print "No image selected/uploaded"; } // Close our MySQL Link mysql_close(); } //End of if statmemnt. ?> On the page which is supposed to display the image upon login in, I inserted the following html code in the div that's supposed to contain the image: <div id="image_box" style="float:left; background-color: #c0c0c0; height:150px; width:140px; border- color:#a0a0a0;border-style:outset;border-width:1px; margin:auto; "> <img src=picscript.php?imname=potwoods> </div> And finally, the picscript.php contained the select query: <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //include the config file require('config.php'); $image = stripslashes($_REQUEST[imname]); $rs = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND cartegoty = 'main' "); $row = mysql_fetch_assoc($rs); $imagebytes = $row[image]; header("Content-type: image/jpeg"); print $imagebytes; ?> Now the million dollar question is, "What is preventing the picture from getting displayed?" I know this is a very lengthy and laborious problem to follow but I'm sure there is someone out there who can point out where I'm not getting it. Thanks. Hi Everyone, I have a program that generates 200 unique images keeping the first image static in each run.The images keep scrolling on to the screen pause for 3 seconds and scroll off I'm able to generated all 200 unique images without repetition, everything is working well except for the lase two images the last two images are scrolling on to the screen but are not been displayed in the database, Moreover The last image is a duplicate of 197th image.I don't know what is happening..... Here is MY code.......... <?php session_start(); $sid = $_SESSION['id']; $_SESSION['imageDispCnt'] = 0; $myQuery = "SELECT * from image"; $conn = mysql_connect("localhost","User","Passwd"); mysql_select_db("database_Name",$conn); $result = mysql_query($myQuery); $img =Array(); $id =Array(); $i =0; $imagepath = 'http://localhost/images/'; while ($row = mysql_fetch_array($result)) { $img[$i] = $imagepath.$row['img_name']; $id[$i] = $row['imageid']; $i = $i + 1; } ?> </head> <script language="JavaScript1.2"> var scrollerwidth='800px'; var scrollerheight='600px'; var scrollerbgcolor='white'; var pausebetweenimages=3200; var s; var sec; var d; var j; var imgid; var milisec = 0; var seconds = 0; var flag = 1; var ses_id = '<?php echo $sid;?>'; var count = 0; var i = 0; var imgname; var imgid; var k =0; var slideimages=new Array(); var img_id = new Array(); var index; <?php $l =0; $count = array(); $j = rand(0,199); while($l < 200) { while(in_array($j, $count)) { $j = rand(0,199); } $count[$l] = $j; $l++; }?> <?php $k = 0; for($k = 0;$k<count($count);$k++){ ?> index = <?php echo $k;?>; <?php $indx = $count[$k];?> if(index == 0){ slideimages[0] = '<img src="http://localhost/images/hbag044.jpg" name="r_img" id="0"/>'; img_id[0] = '<input type="hidden" value="0" id="imgId" />'; } else if(index > 0) { slideimages[<?php echo $k?>] = '<img src="<?php echo $img[$indx]?>" name="r_img" id="<?php echo $id[$indx]?>"/>'; img_id[<?php echo $k?>] = '<input type="hidden" value="<?php echo $id[$indx]?>" id="imgId" />'; } <?php } ?> Can Any one plese help me Appreciate your help... Thanks Okay, so here is the deal. Have a table which stores image as blob files. Now i want to read the image width and height directly from the blob field. Is this possible and if yes, how? Things i tried so far; list($size[0],$size[1],$type, $attr) = getimagesize('image.php?i=26ddd45b02859e836d13d4b9fde34281'); print_r($size); $img = 'image.php?i=26ddd45b02859e836d13d4b9fde34281'; echo imagesy($img); image.php grabs the image from DB and show's it with header("Content-type: image/jpg"); It works for just showing the images with the <img> tag. Any ideas of help would be great! wrote a stored procedure this morning and i don’t know how to get the values out of it through a class function in php or phpmyadmin. here is what i wrote : public function totalProcedures($friend_name,$session_id) { /* *query to fetch stored procedure */ try { //executing the stored procedure $sql_sp="CALL timeline (:friend, :session,@updates, @group_posts)"; $stmt_sp= $this->_db->prepare($sql_sp); $stmt_sp->bindValue(":friend",$friend_name); $stmt_sp->bindValue(":session",$session_id); $stmt_sp->execute(); $rows=$stmt_sp->fetch(PDO::FETCH_ASSOC); $stmt_sp->closeCursor(); // closing the stored procedure //trying to get values from OUT parameters. $stmt_sp_2=$this->_db->prepare("select @updates,@group_posts"); $stmt_sp_2->execute(); return $stmt_sp_2->fetch(PDO::FETCH_ASSOC); } catch (PDOException $ei) { echo $ei->getMessage(); } } can someone helpme how to get results. here is the storedprocedu DELIMITER $$ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeline`(IN `friend` VARCHAR(255), IN `session_id` VARCHAR(255), OUT `updates` VARCHAR(62555), OUT `group_posts` VARCHAR(62555)) BEGIN select * FROM updates where author in (friend,session_id) order by time desc limit 5; select * FROM group_posts where author_gp in (friend,session_id) order by pdate desc limit 5; END$$ DELIMITER ; i get the result in php myadmin as follows:
how do i do this inside a php class function. CALL timeline('shan2batman','aboutthecreator', @updates, @group_posts);
The path to a image is stored in a variable and I need to display this image in the email. Can someone help me. This is my current attempt and nothing is happening. But the variable passes the URL correctly. Code: [Select] <TABLE BORDER='0'> <TR> <TD align='left' width='370'><img src='".$dis_logoimg."' width='370' height='86' /></TD> </TR> </TABLE> Often times I need to convert between PHP Arrays, MySQL, XML, JSON sqlite etc. Lately I've been just building PHP arrays with all the data. Its a big hassle though when theres a lot of data. I'm thinking I should have one central location that I store data in, then export to other formats from there, but I dont know what that central location should be. I like MySQL because I'm used to it. Sometimes its not an option though, like if I need to make a really light script, I dont want the hassle of connecting to MySQL. Would XML be the best place to store data, then from the XML file I can convert it to whatever format I want?
Hi Everyone, I have this php page that runs couple of MS SQL stored procedures to fetch me values from SQL Server, however I have run into a problem where not more then 2 stored procedures are executed at same time. For instance below mentioned code only fetches me values for 1st and 2nd SP's. If I need values from the 3rd stored procedure then I would have to comment either one of the first two stored procedure. Can someone please tell me what is that I am doing wrong. I am relatively new to PHP, so please be gentle. Any help would be highly appreciated. Thanks. <?php if($conn = mssql_connect('host', 'user', 'pass')) echo 'Connected to SQLEXPRESS<BR>'; if(mssql_select_db("database",$conn)) echo 'Selected DB: SomeDatabase<BR>'; $variable1=something; $sql_statement = mssql_init("stored_procedure1 '$variable1'", $conn); $result=mssql_execute($sql_statement); $x=0; while ($row = mssql_fetch_assoc($result)) { $column2[$x]= $row['column2']; $column1= $row['column1']; $x++; } echo "Value 1: $column1 </br>"; echo "Value 2: $column2[0] </br>"; echo "Value 3: $column2[1] </br>"; echo "Value 4: $column2[2] </br>"; echo "Value 5: $column2[3] </br>"; echo "Value 6: $column2[4] </br>"; echo "Value 7: $column2[5] </br>"; mssql_free_statement($sql_statement); $sql_statement = mssql_init("stored_procedure2 '$variable1'", $conn); $result=mssql_execute($sql_statement); $x=0; while ($row = mssql_fetch_assoc($result)) { $someval1[$x]= $row['somecolumn1']; $someval2[$x]= $row['somecolumn2']; $someval3= $row['somecolumn3']; $someval4= $row['somecolumn4']; $someval5= $row['somecolumn5']; $someval6= $row['somecolumn6']; $x++; } echo "Something1: $someval1[0]</br>"; echo "Something2: $someval3 </br>"; echo "Something3: $someval2[0] </br>"; echo "Something4: $someval4 </br>"; echo "Something5: $someval6 </br>"; echo "Something6: $someval5 </br>"; mssql_free_statement($sql_statement); $sql_statement = mssql_init("stored_procedure3 '$variable1'", $conn); $result=mssql_execute($sql_statement); $x=0; while ($row = mssql_fetch_assoc($result)) { $somevaluecheck= $row['somecolumncheck']; $x++; } echo "SomethingCheck: $somevaluecheck </br>"; mssql_free_statement($sql_statement); ?> I'm working on a project and cannot figure out why one piece of code works in one project but not in this one. Code: [Select] $username = "voltageme5"; $result = $mysqli->query("call usernameCheck($username)"); returns string(43) "Unknown column 'voltageme5' in 'field list'" Here is the stored routine: Code: [Select] CREATE PROCEDURE `database`.`table` (IN memUsername varchar(45)) BEGIN select count(*) as total from members where username = memUsername; END Whats weird is that in the PHP code if i replace the variable with a string, it works. It's only with the variable in the call that it errors out like that. I'm new to this stored procedure thing so I'm sure I'm missing something stupid. Hey Guys, I have got 3 chained select boxes working. Basically what you do is check for a region with the country, then once you pick a region, you select a club within that region. Once you have selected the club, you can then choose a team from within that club. Screenshot: Attchment As part of this chained select boxes's, a user can register. Although, the user has to FIRST check if the TEAM has already been registered in the database. I have taken a screenshot of my database, which shows the regions, clubs, and teams from the chained select boxes. What i want to do now is be able to check if a TEAM is already registered in the database. So as you can see in the database, the team 'NPOB, Senior As' has already been taken. Database Screenshot: Attachment *** How do i check if a user has been registered to one of the teams? And if there is not a registered user to that team, they can then register it. Here is my code: <?php include"database.php"; ?> <script type="text/javascript"> /* Triple Combo Script Credit By Philip M: http://www.codingforums.com/member.php?u=186 Visit http://javascriptkit.com for this and over 400+ other scripts */ var categories = []; categories["startList"] = ["Taranaki","Auckland"] // Regions + Clubs categories["Taranaki"] = ["NPOB","Tukapa"]; categories["Auckland"] = ["Marist","Takapuna"]; // Clubs + Teams within that Club categories["NPOB"] = ["Senior As","Senior Bs","Colts U21s"]; categories["Tukapa"] = ["Senior As","Senior Bs","Colts U21s"]; categories["Marist"] = ["Senior As","Senior Bs","Colts U21s"]; categories["Takapuna"] = ["Senior As","Senior Bs","Colts U21s"]; var nLists = 3; // number of select lists in the set function fillSelect(currCat,currList){ var step = Number(currList.name.replace(/\D/g,"")); for (i=step; i<nLists+1; i++) { document.forms['tripleplay']['List'+i].length = 1; document.forms['tripleplay']['List'+i].selectedIndex = 0; } var nCat = categories[currCat]; for (each in nCat) { var nOption = document.createElement('option'); var nData = document.createTextNode(nCat[each]); nOption.setAttribute('value',nCat[each]); nOption.appendChild(nData); currList.appendChild(nOption); } } // function getValue(L3, L2, L1) { // alert("Your selection was:- \n" + L1 + "\n" + L2 + "\n" + L3); // } function init() { fillSelect('startList',document.forms['tripleplay']['List1']) } navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false); </script> <form name="tripleplay" action="testingdropdown.php" method="post"> <select name='List1' onchange="fillSelect(this.value,this.form['List2'])"> <option selected>Choose Region</option> </select><br /><br /> <select name='List2' onchange="fillSelect(this.value,this.form['List3'])"> <option selected>Choose Club </option> </select><br /><br /> <select name='List3' onchange="getValue(this.value, this.form['List2'].value, this.form['List1'].value)"> <option selected >Choose Team </option> </select> <input type="submit" name="tripleplay" value="Register"> </form> <?php if (isset($_POST['tripleplay'])) { $region = addslashes(strip_tags($_POST['List1'])); $club = addslashes(strip_tags($_POST['List2'])); $team = addslashes(strip_tags($_POST['List3'])); $email = 'email'; $check = mysql_query("SELECT * FROM managers WHERE email='$email'"); if ($email == '') { echo "You can register that club"; } else { echo "Sorry that team has already been registered"; } } ?> I have a PHP page that offers various information from a single text file. This text file is encrypted on the server HD. Upon initial entry into the page, the user enters an encryption/decryption KEY and the encrypted file is decrypted to clear text and it is available for viewing. I have some parameters that I store in PHP session variables. I do this since various subsequent actions by the user will require these parameters. The code is written and the whole process seems to work well. Since the info in these session variables is sensitive, I need to understand WHERE they are stored. I know that it is a file on the HD, but after hours of reading the PHP Manual on sessions, I am not finding where (HD directory) that storage is. I have a typical shared hosting account for my web site. Mostly I want to discover is, are the session variables in y User/file hierarchy, or are they stored in a system area where the PHP is installed. Whew. Sorry this was so long.
Thank you, I am trying to make a setup file for a website I'm developing, and am having the database tables and stored procedures created automatically. However, I'm having issue getting the stored procedures to be created. Here is my code: Code: [Select] $db->Q(" DELIMITER $$ CREATE PROCEDURE `Database`.`Procedure_Name`(in sp_uid mediumint(20) unsigned, in sp_user varchar(15), in sp_pass varchar(20), in sp_email varchar(30)) BEGIN Insert Into Table Values (sp_uid, sp_user, md5(sp_pass), sp_email, '1', '1', '0'); Select true; END$$ "); Assume that the "$db->Q()" works just fine, as I'm having issues no where else with it. This automatically connects to the database and runs a query with whatever is inside the "()". The tables are being created just fine, but no stored procedures are being created. I've tried everything I can think of, and googled my question many different ways without finding an answer or work-through. Does anyone know what I am doing wrong? Thanks in advance. hey guys i have this code FILE NAME "index.php" Code: [Select] <?php // make a connection to the database mysql_connect ("localhost", "root", "vertrigo") or die ('Error: I Failed To Connect To The Database ' . mysql_error()); mysql_select_db ("test"); // Get Data $query = mysql_query("SELECT * FROM TestTable"); // display the data and loop while ($row = mysql_fetch_array($query)) { echo "<br /> ID: ".$row['ID']."<br /> First Name: ".$row['FName']."<br /> Last Name: ".$row['LName']."<br /> Contact Number: ".$row['CNumber']."<br />";} ?> <form method="post" action="update.php"> <table border="1" align="center"> <tr> <td align="right" width="220">ID: </td> <td align="left" width="220"> <input type="text" name="ID" size="30" /></td> </tr> <tr> <td align="right" width="220">First Name: </td> <td align="left" width="220"> <input type="text" name="FName" size="30" /></td> </tr> <tr> <td align="right" width="220">Last Name: </td> <td align="left" width="220"> <input type="text" name="LName" size="30" /></td> </tr> <tr> <td align="right" width="220">Contact Number: </td> <td align="left" width="220"> <input type="text" name="CNumber" size="30" /></td> </tr> <tr> <td align="right" width="220"><input type="reset" value="Reset" /> </td> <td align="left" width="220"> <input type="submit" value="Update Database" /></td> </tr> </table> </form> and i also have this code FILE NAME "update.php" Code: [Select] <?php $ID = $_POST['ID']; $FName = $_POST['FName']; $LName = $_POST['LName']; $CNumber = $_POST['CNumber']; mysql_connect ("localhost", "root", "vertrigo") or die ('Error: I Failed To Connect To The Database ' . mysql_error()); mysql_select_db ("test"); $query="INSERT INTO testtable (ID, FName, LName, CNumber)VALUES ('".$ID."','".$FName."', '".$LName."', '".$CNumber."')"; mysql_query($query) or die ('Error Updating Database'); echo "Database Updated Sucsessfully With: ".$ID." ".$FName." ".$LName." ".$CNumber ; ?> ok so the script is working like a charm its sending the data to the database as i want it to. the problem i have is that i want to be able to update the info that is already on the database lets say i want to change a phone/contact number i have typed the ID number into the ID text field and the same first and last name into there correct boxes and then typed in the new phone number i then click submit and i get the error ""Error Updating Database"" i have looked all over the forum and net to see what i have done wrong to not allow this code to update can anyone help me out here please im quite new to the php language and could really do with some pointers thanks Steve How can I run php code that is stored in a database? I have my pages created by grabbing the contents of a pageBody mySQL table cell, but some pages require further php to be able to display correctly. For example, I have a players page, which will list all players, and some information about them. The players and information is all saved in a players table in my database (separate to the pages table where pageBody is stored). I use simple php to grab all the players and format all of their information so it can be displayed on the page. This is the flow of information that I would like: User clicks on players page browser loads content page (this is a template page), and grabs the pageid from $_GET browser then reads pages table in database to get the pageBody associated with the pageid The pageBody will contain more php, which will run the players script to retrieve the list, and display Doing it the above way will make it much easier to extend the website to include more types of pages that has to run additional php scripts. The only way I can think of this working is by doing this: user clicks on players page browser loads content page, grabs pageid from $_GET browser checks the pageid for the one associated with players (hard coded into the php script) browser then loads the players.php script instead of going to the database This above way means that I will need to edit the index.php page everytime I add a new list type (example, coaches, volunteers etc). Anyone have any suggestions? I know my question is long, but I was finding it hard to explain it in an easy to understand way, but I'm still not sure if I have :S. Cheers Denno Hey guys, I have been banging my head against a wall here with this. I am saving my sessions in my database via session_set_save_handler(). So let me walk you through what I have here, what works, and what the issue seems to be. basically, the problem is the $_SESSION array is empty on page load. common.php: I have the open / close / read / write / destroy / and gc functions. These all work properly as when i use a session variable it stores into the database and i can see all of the information in there.. inside of common.php i have session_start().. I am positive that the session_start() is running becasue common.php is included into index.php and i tried adding session_start() to index.php again and i got an E_NOTICE saying the session already began. (yes, for the read function i am returning a string... i included that below). for the table itself, i have set the session_data as both text and blob, same issue with both. index.php: includes common.php. I know it's included as other aspects of the file are included and work properly. if i call var_dump($_SESSION) i get an empty array. and i prited out the session_id() and it matched my session id in the database. and the values that are stored in there are correct. i have for example: count|i:0 now with that value actually in the database and when calling session_id() and i get the ID that matches in the table. so i will get an E_NOTICE of an undefined index.. i was trying something like: if(!isset($_SESSION['count'])) $_SESSION['count'] = 0; else $_SESSION['count']++; echo $_SESSION['count']; Everytime the page is reloaded, count is reset to 0.. I can tell that it is reset to 0 as the expired time changes in the database after every load of the page (which is part of the write function). I double checked that it wasn't a problem for some reason with the ++ by adding in a variable that sets to 1 when in the if, and 0 if in the else, and it always outputs a 1. i have included here my read function since that apparently is the issue.. function sess_read($sess_id) { global $DB; $sql = "SELECT `session_data` FROM `sessions` WHERE session_id = '".$sess_id."' AND session_agent = '".$_SERVER["HTTP_USER_AGENT"]."' AND session_expire > '".time()."';"; $query = $DB->query($sql); if($DB->num_rows($query) > 0) { $r = $DB->fetch($query); return settype($r['session_data'], 'string'); } return ''; } I tried also with removing the agent and expire check to see if it was an issue there but same problem. I probably have missed something really dumb but i can't for the life of me figure it out and I have googled around for a similar issue. The actual output of the page is correct.. all of the HTML and CSS information loads properly.. no errors are reported (and i have E_ALL on). Thanks Hello, Here's my system. Once a user is successfully logged in, a new instance of a User class is created. The constructor of this class grabs the details of the logged-in user from a database and stores them inside properties in the User class. The problem is, obviously I'd want to access these properties from any page I require them to be able to display user data, so I looked into storing the User object in a Session. When I tried implementing this, I ran into a bunch of errors and I couldn't figure it out. Here's an example: After a user has logged in, I had the following code: Code: [Select] $_SESSION['user'] = new User($this->username); I was under the impression that this assigns a user object to a session. But it's not working as I receive this error: Quote Notice: Undefined index: user in ../v2/admin/index.php on line 18 Then on the page I want to display the name of the current user logged-in, I had this code: Code: [Select] $_SESSION['user']->get_Name(); But then I get this error: Quote Fatal error: Call to a member function get_IP() on a non-object in ../v2/admin/index.php on line 18 Can tell me what I have to do, to make this work? Thanks. Hi All, I'm hitting brick walls while trying to run a stored procedure query with PDO (linking to MSSQL) If I run the query from SSMS (SQL Server Management Studio) I get a result every time (one single row is returned, as expected) - I'm placing the same query into PHP without any dynamic variables etc - its just a straight query... when it runs the query in PDO it fails every time with this error:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[IMSSP]: The active result for the query contains no fields.' in index.php:195 The code is as follows: $SQLSTMTA="exec pEmployeeGetData @EmployeeID='1',@Year='2020'"; $STHA = $DBH2->prepare($SQLSTMTA); //$STH->bindParam(':EMPID', $EmployeeID); $STHA->execute(); while($result = $STHA->fetchAll()) { //(row 195) var_dump($result); } I've also tried a few variations on the above such as ->Fetch (as opposed to FetchAll) without any luck. Any ideas on how I can get around this? Thanks in Advance!
Hi Guys, I have a webpage which has subsequent pages stored in a database e.g. index.php?id=1 The problem being, is that id=1 has it's data pulled from a database. This was fine & dandy until I started to insert PHP...I am trying to get the below to executre <?php $rater_id=1; $rater_item_name='Rate This'; include("rater.php");?> However nothing shows & nothing happens, I know eval can be used but have not been succesfull in implementing this, can someone please help! i have made a logon script but he must give a output parameter "relatieid" but if i do print relatieid i don't get the output parameter. what can i do to get the output parameter. i must give -1 if your logon data don't be good and your relatie id if you are succesfull logon. i saw that you can use fatchall but how my script is: php Code: [Select] <?php session_start(); $sessieid = session_id(); error_reporting(-1); ini_set('display_errors', 1); if($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; $wachtwoord = $_POST['wachtwoord']; $ip = $_SERVER["REMOTE_ADDR"]; $computernaam = php_uname('n'); if(trim($username) == '') { echo "<font color='red'>Vul geldige gebruikersnaam in!</font><br>"; header("refresh:5;url=/login/"); exit() ; } if(trim($wachtwoord) == '') { echo "<font color='red'>Vul geldige wachtwoord in!</font><br>"; header("refresh:5;url=/login/"); exit() ; } $db = new PDO('mssql:host=localhost\snelstart;dbname=SluisWWW','test','********'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $db->prepare("EXECUTE spMagInvoeren ?,?,?,?,?,?,?"); $stmt->bindValue(1 ,$username, PDO::PARAM_STR); $stmt->bindValue(2 ,$wachtwoord); $stmt->bindValue(3 ,$ip); $stmt->bindValue(4 ,$computernaam); $stmt->bindValue(5 ,$sessieid); $stmt->bindParam(6 ,$poging); $stmt->bindParam(7 ,$relatieid); $stmt->execute(); print "<br/>Returned: $relatieid<br/><br/>\r\n"; { setcookie("TestCookie", $username); // redirecten exit(); } } stored procedure ms sql server Code: [Select] USE [SluisWWW] GO /****** Object: StoredProcedure [dbo].[spMagInvoeren] Script Date: 04/04/2012 09:54:59 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Henk Boessenkool -- Create date: 23 Maart 2012 -- Description: test login -- ============================================= ALTER PROCEDURE [dbo].[spMagInvoeren] -- Add the parameters for the stored procedure here @Usernaam nVarchar(20) , @Wachtwoord nvarchar(20), @IPAdres nvarchar(20), @Computer nvarchar (20), @SessieID nvarchar(50), @PogingenOver integer OUTPUT, @RelatieNummer integer OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. DECLARE @Success INT SET NOCOUNT ON; SET @Success = (SELECT COUNT(*) FROM contactpersonen WHERE (username = @Usernaam AND wachtwoord = @Wachtwoord)) IF @Success = 1 BEGIN SET @RelatieNummer = (SELECT TOP 1 relatie_id FROM [SluisWWW].[dbo].[contactpersonen] WHERE (username = @Usernaam AND wachtwoord = @Wachtwoord)) END ELSE SET @RelatieNummer = -1 INSERT INTO [SluisWWW].[dbo].[Logins] (Login,Wachtwoord,RelatieID,IP,Computer,SessieID) VALUES (@Usernaam,@Wachtwoord,@RelatieNummer,@IPAdres,@Computer,@SessieID) set @PogingenOver = 24 -- Insert statements for procedure here END i'm stuck with searching on age query i let users register their date of birth (they give in DAY, MONTH, YEAR) --> column 3 Name CalcAge Timestamp Timestamp calculated for query Person 1 21 659948401 642754801 Person 2 39 91954801 83746801 Person 3 15 849337201 848991601 Person 4 33 281257201 281170801 Person 5 23 596876401 600850801 Person 6 87 -1422809999 -1422723599 I came up with the following query to search between a minimum and maximum age (using AJAX): Code: [Select] //user enters a minimum and/ or max age - getting the querystring from URL (ajax) $minAge = $_GET['minAge']; $maxAge = $_GET['maxAge']; //age to unix timestamp function agetostamp($age){ $gebjaar = date(Y) - $age; $timestamp = mktime (0,0,1,0,0,$gebjaar); return $timestamp; } //making getvariables timestamp in order to compare with database if (isset ($minAge)){ $minAge = agetostamp($minAge); } if (isset ($maxAge)){ $maxAge = agetostamp($maxAge); } //building query query = "SELECT * FROM respondenten WHERE geslacht = '$sex'"; if(is_numeric($minAge) && $minAge > 0) $query .= " AND geboortedatum <= '$minAge'"; else if (is_numeric($minAge)) $query .= " AND geboortedatum >= '$minAge'"; if(is_numeric($maxAge) && $maxAge > 0) $query .= " AND geboortedatum <= '$maxAge'"; else if (is_numeric($minAge)) $query .= " AND geboortedatum >= '$maxAge'"; I encouter a lot of troubles working like this: 1) if i leave out the part of maxAge (so i only allow to set a minimum age in the search box) it works except for the fact that if i set the minimum age to 23, person 5 will not be included since 596876401 < 600850801 even though she is 23 and should be included. 2) if i add the part of also searching on a max age, i don't get any results I know that remark 1 probably has to do with the fact that im using date(Y) - $age and that people that are already born this year will have a timestamp higher than the one calculated in the query and visa versa. conclusion: i don't think i'm going to get out of this so i'm hoping sombody can help me, telling me how to build a query for selecting on age range |