PHP - Unique Reference
Hi,
I just need someone to check that a couple of lines I've written do what I believe them to do... i.e. check my logic! I'm developing a booking form for booking on events. Each booking needs a unique reference, which needs to be meaningless to the customer, so I am BASE36 encloding it. As the booking is be saved to a MySql database, my approach is to use the auto-incremented ID for the record to make the reference unique. The increment starts at 10000, and I add a random number before coding to make the encoded reference longer. I then BASE36 encode it to make it appear random. Am I right in thinking the reference produced WILL be unique ... provided the auto-inc ID is unique? $ref = rand(100,999) . $auto_incremented_id; //e.g. 354 & 10012 = 35410001 $ref_encoded = strtoupper(base_convert($rand, 10, 36)); // e.g.UD4J8P Thanks Similar Tutorialsfirstly, apologies on my TOPIC TITLE. i couldnt think of how better to write it.
anywho, i am inserting a new row of data into a table. immediately after inserting it, i want to select the unique value in the 'id' row. two questions.
1. how can i reference this newly inserted row if the only unique value is the id (primary auto-increment)?
2. is there a way to insert this new row AND select that id value in one query?
I have a mysql table which will store users email addresses (each is unique and is the primary field) and a timestamp. I have added another column called `'unique_code' (varchar(64), utf8_unicode_ci)`. What I would very much appreciate assistance with is; a) Generating a 5 digit alphanumeric code, ie: 5ABH6 b) Check all rows the 'unique_code' column to ensure it is unique, otherwise re-generate and check again c) Insert the uniquely generated 5 digit alphanumeric code into `'unique_code'` column, corresponding to the email address just entered. d) display the code on screen. What code must I put and where? **My current php is as follows:** Code: [Select] require "includes/connect.php"; $msg = ''; if($_POST['email']){ // Requested with AJAX: $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ throw new Exception('Invalid Email!'); } $mysqli->query("INSERT INTO coming_soon_emails SET email='".$mysqli->real_escape_string($_POST['email'])."'"); if($mysqli->affected_rows != 1){ throw new Exception('You are already on the notification list.'); } if($ajax){ die('{"status":1}'); } $msg = "Thank you!"; } catch (Exception $e){ if($ajax){ die(json_encode(array('error'=>$e->getMessage()))); } $msg = $e->getMessage(); } } Hi all, I have been coding in PHP for a fair while now and I have come across variables by reference, but I don't really know: a) how they work; b) when to use them; c) why they are used; Can anyone here please clarify these issues please. Thanks in advance! hello. say i have list and i want the correct children under each parent so i have $id $parent_id $type $name in the db i have 4 parents each with 2 children id=1 - type=parent - parent_id=0 - name=p1 id=2 - type=parent - parent_id=0 - name=p2 id=3 - type=parent - parent_id=0 - name=p3 id=4 - type=parent - parent_id=0 - name=p4 id=5 - type=child - parent_id=1 - name=c1 id=6 - type=child - parent_id=1 - name=c2 id=7 - type=child - parent_id=2 - name=c3 id=8 - type=child - parent_id=2 - name=c4 id=9 - type=child - parent_id=3 - name=c5 id=10 - type=child - parent_id=3 - name=c6 id=11 - type=child - parent_id=4 - name=c7 id=12 - type=child - parent_id=4 - name=c8 so how would i do the code? i thought i could do it like this but its not working. Code: [Select] <?php $family = Family::find_all(); foreach($family as $familys){ $id = $familys->id; $type = $familys->type; $parent_id = $familys->parent_id; $name = $familys->name; echo' <ul>'; if($type == "parent"){ echo $name; } echo' </ul> <li>'; if($type == "child" && $parent_id == $id){ echo $name; } echo' </li>'; } ?> all i get back is p1 p2 p3 p4 no children ?? if i remove Quote $parent_id == $id from Quote if($type == "child" && $parent_id == $id){ i get this p1 p2 p3 p4 c1 c2 c3 c4 c5 c6 c7 c8 but they are not listed under the correct parent i also tried moving the </ul> to the bottom but i get the same Code: [Select] <?php $family = Family::find_all(); foreach($family as $familys){ $id = $familys->id; $type = $familys->type; $parent_id = $familys->parent_id; $name = $familys->name; echo' <ul>'; if($type == "parent"){ echo $name; } echo' <li>'; if($type == "child"){ echo $name; } echo' </li> </ul>'; } ?> any thoughts? thanks rick Hello, I've just started learning PHP, JavaScript and I've got a big problem on my website. I'm getting this ReferenceError. I know what's the problem, but I don't know how to solve it, and I know people can do it for money but I don't have money, I'm searching for someone who's willing to help newbie. As I said I'm begginer, and I know something. The main problem is because I want to use GKPlugin and Player(jwplayer). Plugin need to use object, example:
<object id="flashplayer" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="600" height="400"> <param name="movie" value="player.swf" /> <param name="allowFullScreen" value="true" /> <param name="allowScriptAccess" value="always" /> <param name="FlashVars" value="plugins=plugins/proxy.swf&proxy.link=http://www.vidbull.com/53qx9uo10k5d" /> <embed name="flashplayer" src="player.swf" FlashVars="plugins=plugins/proxy.swf&proxy.link=http://www.vidbull.com/53qx9uo10k5d" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="600" height="400" /> </object>Script is generetad just to embed with iframe, and the problem is when I replace it with object, then I'm getting this error. I know that JS can't "call" that iframe to show because I've replaced it with object. You guys probably know about what I'm talking. I'm just searching for some instructions, guidelines from you. ReferenceError: embeds is not defined if (embeds[embedid].indexOf("rapidplayer")== iframe_ad){Here's the rest of code, I think it's used to show iframe. elseif (substr_count($link,"gorillavid")){ $video_id = explode("/",$link); if (isset($video_id[count($video_id)-1])){ $video_id = $video_id[count($video_id)-1]; $embed = '<object id="flashplayer" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="600" height="400"> <param name="movie" value="http://www.kiinc.com/videott/player.swf" /> <param name="allowFullScreen" value="true" /> <param name="allowScriptAccess" value="always" /> <param name="FlashVars" value="plugins=http://www.kiinc.com/videott/plugins/proxy.swf&proxy.link=http://gorillavid.in/'.$video_id.'" /> <embed name="flashplayer" src="player.swf" FlashVars="plugins=http://www.kiinc.com/videott/plugins/proxy.swf&proxy.link=http://gorillavid.in/'.$video_id.'" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="600" height="400" /> </object>'; This is the original code. Don't look at providers(source as gorillavid) because I used gorillavid in previous an posted another example from another source (zalaa) elseif (substr_count($link,"zalaa")){ $video_id = explode("/",$link); if (isset($video_id[count($video_id)-1])){ $video_id = $video_id[count($video_id)-1]; $embed = '<IFRAME SRC="http://www.zalaa.com/embed-'.$video_id.'.html" FRAMEBORDER=0 MARGINWIDTH=0 MARGINHEIGHT=0 SCROLLING=NO WIDTH='.$width.' HEIGHT='.$height.'></IFRAME>'; Function which embed links and should embed GKPlugin/Player: // general image link if (!$embed){ $embed = "<div style='background-color:#000000; width: ".$width."px; height: ".$height."px;text-align:center;cursor:pointer;' onclick='window.open(\"$link\");'>"; $embed.= "<p style='text-align:center; padding-top: 70px;'>"; $embed.= "<a href='$link' target='_blank' style='font-size:24px; color: #ffffff !important'>Click here to play this video</a>"; $embed.= "</p>"; $embed.= "</div>"; } return $embed; } JavaScript code: function getEmbed(embedid){ if (embeds[embedid].indexOf("rapidplayer")== iframe_ad){ var html_content = "<div class='fake_embed' id='fake_embed"+embedid+"' onclick='closeFakeEmbed("+embedid+");'>" + "<br /><br />" + "<div class='fake_embed_ad_close'><a href='javascript:void(0);' onclick='closeFakeEmbed("+embedid+");'>Close Ad</a></div>" + "<div class='fake_embed_ad' id='fake_embed_ad" + embedid +"'>" + "<iframe src='"+baseurl+"/iframe_ad.php' width='300' height='300' frameborder='NO' border='0'></iframe>" + "</div>" + "<div class='fake_embed_bar'><span class='fake_embed_bar_right'></span></div>" + "</div>" + "<div id='real_embed"+embedid+"' style='display:none'>"+embeds[embedid]+"</div>"; jQuery('#videoBox'+embedid).html(html_content); jQuery('#videoBox'+embedid).show(); } else { jQuery('#videoBox'+embedid).html(embeds[embedid]); jQuery('#videoBox'+embedid).show(); } } function countDown(embedid){ showCounter = showCounter-1; jQuery('span#counter').html(showCounter); if (showCounter>0){ showTimer = setTimeout('countDown('+embedid+');',1000); } else { showTimer = null; showCounter = 20; getEmbed(embedid); } } function changeEmbed(embedid, counter){ if (counter == 0){ jQuery('.embedcontainer').html(''); jQuery('.embedcontainer').hide(); getEmbed(embedid); } else { if (showTimer){ clearTimeout(showTimer); } showTimer = null; showCounter = counter; jQuery('.embedcontainer').html(''); jQuery('.embedcontainer').hide(); jQuery('#videoBox'+embedid).html(js_lang.ticker); jQuery('#videoBox'+embedid+' span#counter').html(showCounter); jQuery('#videoBox'+embedid).slideDown("slow"); showTimer = setTimeout('countDown('+embedid+');',1000); } /* jQuery('li.selected').removeClass('selected'); jQuery('#selector'+embedid).addClass('selected'); */ } Can someone explain this strange behavior: $aArray = array( 1 => null, 2 => null, 3 => null, ); foreach($aArray as $key => &$val) { $val = "Some Value"; foreach($aArray as $Xkey => $Xval){} // Second foreach } var_dump($aArray); Rsult is: array(3) { [1]=> string(10) "Some Value" [2]=> NULL [3]=> NULL } It looks like second foreach breaks reference, why? Dear All, Am new to PHP. now i want to online cargo tracking system in php. in that i create the reference id for each user to track the shipments. in that user must login and track the shipments. now i need the code for the specific user only view they shipments only. the other user can't be check the other shipments. so i need how to link the user and reference id. kindly advice me. Hi everyone, This is driving me crazy. I need to reference different files located in different folder structure. For example, I have the following file structure. /my_project/ /my_project/database/database_script.php /my_project/index.php 1. If I want to reference /my_project/index.php from /my_project/database/database_script.php, how can I reference it ? 2. From /my_project/index.php to /my_project/database/database_script.php , it's obvious all I gotta do it include("/database/database_script.php"). I use $_SERVER('DOCUMENT_ROOT"), to solve the 1. problem. It works on my XAMPP local machine but when I uplode it onto the server, there's a problem. The path becomes '/my_project/my_project/database/database_script.php". Is there a universal way (more like a standard way) to reference files in php so that I won't need to change every file path once I upload those onto the server ? Regards, 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; } If getValue is given a path which doesn't exist, I can use the isset check to return null. I can also use the uncommitted $tmp =&$tmp[$key];. Why does this prevent an undefined index warning?
public function getValue(string $path) { $path=explode('.', $path); $tmp=$this->config; foreach($path as $key) { //if(!isset($tmp[$key])) return null; //$tmp =$tmp[$key]; $tmp =&$tmp[$key]; } return $tmp; }
Hi Guys Probably a simple answer to this. Writing a script where I have a foreach to escape data in a multi dimensionsal array - destined for the database. I want to preserve the the escaped values in the array so I've passed in the value by referece. See code below: Code: [Select] foreach($myarray as $key=>$value){ foreach($value as $k=>$v){ $v = $mysqli->real_escape_string(&$v); echo $v ."<br/>"; } } I've switched on error_reporting(E_STRICT), because i read it was good practice to build your scripts with this on. Anyway - when i pass by reference I get a message as follows: Quote Deprecated: Call-time pass-by-reference has been deprecated in C:\wamp\www\wh\C.php on line 105 So if pass by reference is deprecated, what's the alternative? I realise i could pass the new values to a new array. But does this mean i shouldn't pass by reference anymore? Many thanks and sorry for going round the planet to ask such a simple question. Drongo Is it possible to get something as a reference in the script if it is such a http://site.com/home#p1 tried in different ways but #p1 my script does not see Hi all, I'm trying to understand passing by reference. Here is a copy of the code and the results: Code: [Select] <?php $a1 = 15; $b1 = 20; echo addone($a1, $b1); echo "<br/>"; function addone($n1, $n2){ $n1 = $n1 += 2; $n2 = $n2 += 2; return $n1 . " " . $n2; }; echo addonetwo($a1, $b1); function addonetwo($n1, $n2){ $n1 = $n1 += 2; $n2 = $n2 += 2; return $n1 . " " . $n2; } ?> The result output is: 17 22 17 22 If I change the code to add "&" before the "addone" function: Code: [Select] function addone(&$n1, &$n2){ $n1 = $n1 += 2; $n2 = $n2 += 2; return $n1 . " " . $n2; }; Then the output is: 17 22 19 24 I don't understand what's going on. Why is the "&" incrementing the changed variable and in the first example it's incrementing the variables as defined. OK, so I have the following file that has database functions: <?php function dbDelete($param){ $conDelete = mysql_connect($url,'username','password',true); mysql_select_db('my_db',$conDelete); mysql_query($param,$conDelete); mysql_close(); if(isset($conDelete)){ mysql_close($conDelete); } } ?> I include the above file in a session handling file. But for some reason the new file can't call the above function as follows: <?php include_once 'the above stated file'; function timeOut(){ dbDelete("DELETE FROM acctussessi WHERE acctussessi_usid = '$sessius[0]'"); $_SESSION = array(); setcookie(session_name(),'',time()-4200); session_destroy(); } //CHECK FOR TIMEOUT REQUEST switch($_GET['xyz']){ case 'timeout': timeOut(); header("Location: /?xyz=timedout"); break; case 'logout': timeOut(); header("Location: /?xyz=loggedout"); break; case 'refresh': dbUpdate("UPDATE acctussessi SET acctussessi_time = ".time()." WHERE acctussessi_unid ='".$token."'"); break; } ?> dbDelete isn't being called inside of the TimeOut() function. The only way it works is by doing the following: <?php function timeOut(){ $_SESSION = array(); setcookie(session_name(),'',time()-4200); session_destroy(); } //CHECK FOR TIMEOUT REQUEST switch($_GET['xyz']){ case 'timeout': dbDelete("DELETE FROM acctussessi WHERE acctussessi_usid = '$sessius[0]'"); timeOut(); header("Location: /?xyz=timedout"); break; case 'logout': dbDelete("DELETE FROM acctussessi WHERE acctussessi_usid = '$sessius[0]'"); timeOut(); header("Location: /?xyz=loggedout"); break; case 'refresh': dbUpdate("UPDATE acctussessi SET acctussessi_time = ".time()." WHERE acctussessi_unid ='".$token."'"); break; } ?> But this is annoying and repetitive. What is going on? Thanks in advance. Hi all, Why when i set my method to returns by reference its giving me a notice that only variables should return by reference while where is not set to return by reference it don't. Fro example: interface i { function &m(); } class a implements i { public function &m() { return $v; } } $v = new a(); $v->m(); So i just return empty $v. Is this a good practice or should i just ignore the notice Ok, starting around line 137 with the functions..... Commented well. Just not sure If im doing it right. Any help greatly appreciated. Basic stuff and still learning. Just trying to figure out if Im passing by reference correctly or if not how to do it. Thanks. php File is attached but heres a snippet. Thanks in advance. Peace, Adam // The grand total and the item total need to be passed BY REFERENCE. function show_table_contents($cart_items, $table, &$grand_total, &$item_total) Hello all, I'm a PHP newbie, so please pardon me if this question has already been asked somewhere in this forum. I have been reading the PHP documentation. On this page http://www.php.net/manual/en/language.references.pass.php, I came across this code: <?php ... snip ... function &bar() { $a = 5; return $a; } foo(bar()); ?> This is returning a reference to local variable $a. Coming from a C/C++ background, my intuition tells me this just shouldn't work, since the local variable $a should be deleted as soon as the function "bar" returns. The code seems to work, though. My guess is that PHP is basically ref-counting and garbage collecting local variables like $a, and so it will not be automatically cleaned up on call exit. Is this about right? Thanks! WN Im trying to understand the code below. (taken from an O'REILLY book) Im trying to get my head around this, so can anyone tell me if im thinking about this in the right way; The function (fix_names) borrows the values from $a1,$a2 and $a3 and puts them into $n1,$n2, and $n3. It then processes the strings contained within these newly created variables and then returns the processed values back into $a1,$a2,and $a3? The variables $n1,$n2, and $n3 cannot be echoed as they were created within the function.? Please correct me if im wrong. Code: [Select] <html> <head> </head> <body> <?php $a1 = "EDWARD"; $a2 = "thomas"; $a3 = "wriGHT"; fix_names($a1,$a2,$a3); echo $a1." ".$a2." ".$a3; function fix_names(&$n1,&$n2,&$n3) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); $n3 = ucfirst(strtolower($n3)); } ?> </body> </html> I think I've gotten as far as I can with my troubleshooting so hopefully someone can help me here. I have a constructor for a controller class that receives the $_SESSION array from index.php by reference. An instance variable is then created when references this references so that any changes made to this instance variable update the real $_SESSION variable. This was working until it mysteriously stopped after not touching it for a few hours. The local $this->session variable is working because it completes some tasks using it. I've also hardcoded values into the session from the index.php file and when they are hard coded the session works as you would expect so it seems to just not be connecting this local variable to the $_SESSION array anymore for some reason. index.php snippet: Code: [Select] session_start(); $action = 'login'; $controller = new UserController($_POST,$_SESSION); call_user_func(array($controller,$action)); constructor and login action from UserController (constructor is actually from a base controller but that shouldn't matter). Also the activeSession() function that checks if a session is valid and kicks the user if its not (which is what happens when anything is tried after logging in): Code: [Select] function __construct($post,&$session){ $this->post = $post; $this->session = &$session; $this->view = 'views/login.php'; $this->title = ''; $this->error = ''; } function login(){ try{ $user = $this->validateString($this->post['username'],'Username'); $pass = $this->validateString($this->post['password'],'Password'); $dao = new UserData(); $this->session['userid'] = $dao->login($user, $pass); $this->session['username']=$user; $dao = new PostData(); $this->posts = $dao->getFeedPosts($this->session['userid']); $this->view = 'views/posts.php'; $this->title = 'Post Feed'; } catch(Exception $e){ $this->handleException($e); } } function activeSession(){ if(!empty($this->session['userid'])) return true; else return false; } Any help would be amazing. I really don't know how this stopped working. Thanks in advance. I am wondering how can I insert integers in the database without manually input it in the form. I am looking to fill the product_id and customer_id table. I would do it but only by sequence and '' quotes at the VALUE part of an INSERT statement. Also condition the insert of product_id and customer_id according to the id in the SESSION variable. Code: [Select] <?php session_start(); if (isset($_SESSION['id'])) { $userid = $_SESSION['id']; $username = $_SESSION['username']; $fname = $_POST['firstname']; $lname = $_POST['lastname']; $telephone = $_POST['telephone']; $city = $_POST['city']; $state = $_POST['state']; $itemname = $_POST['product_name']; $price = $_POST['price']; $details = $_POST['details']; $category = $_POST['category']; $subcategory = $_POST['subcategory']; $product_id = $_POST['product_id']; $customer_id = $_POST['customer_id']; $date_sold = $_POST['date_sold']; $sqlinsert = "INSERT INTO customers (id,firstname,lastname,telephone,city,state,product_name,price,details) VALUES('','$fname','$lname', '$telephone','$city','$state','$itemname','$price','$details')"; $sqlinsert2 = "INSERT INTO products (id,product_name,price,details,category,subcategory) VALUES('','$itemname','$price','$details','$category','$subcategory')"; $sqlinsert3 = "INSERT INTO sales (id,product_id, customer_id, date_sold) VALUES('','$product_id','$customer_id','$date_sold')"; $enterquery = mysql_query($sqlinsert) or die(mysql_error()); $enterquery2 = mysql_query($sqlinsert2) or die(mysql_error()); $enterquery3 = mysql_query($sqlinsert3) or die(mysql_error()); } ?> The above insert its respective fields in each table but how is it possible to INSERT it according to the SESSION['id]; so that it INSERT according to the costumer id plus that it generates and INSERT automatically in the product_id and customer_id related to the product_id and customer_id fields in products and customer table? without manually doing it. any references will be appriciated because the above code seems like the product_id and customer_id won't INSERT in relations to the customer and product table. One more thing the product_id and customer_id won't be pass from the form to this file but rather a value will be INSERT it in their field according to the id in customer and products table. |