PHP - Generating Php Random User Id And Save Into Mysql
Hi
I am using php5 and Mysql I want to generate user id like phone format (Ex: xxx-xxx-xxxx). and check that user id exists in database or not. if yes, i have to generate new user id etc. If that user id not in database, i have to insert user id for new user. Means i have generate unique user id for login purpose. Generating user id is working fine. availability of user id also ok for me by using mysql_num_rows() function. But if user id i exists in database, how can i generate new user id. All this will be done in single instance (When user click on submit button from registration form). Here is my script. Code: [Select] <?php function UserID() { $starting_digit=5; $first_part1=rand(0,99); if(strlen($first_part1)==1) { $first_part="0".$first_part1; } else { $first_part=$first_part1; } $second_part1=rand(1,999); if(strlen($second_part1)==1) { $second_part="00".$second_part1; } elseif(strlen($second_part1)==2) { $second_part="0".$second_part1; } else { $second_part=$second_part1; } $third_part1=rand(1,9999); if(strlen($third_part1)==1) { $third_part="000".$third_part1; } elseif(strlen($third_part1)==2) { $third_part="00".$third_part1; } elseif(strlen($third_part1)==3) { $third_part="0".$third_part1; } else { $third_part=$third_part1; } $userid=$starting_digit.$first_part."-".$second_part."-".$third_part; return $userid; } $random_userid=UserID(); $sql=mysql_query("select * from users where user_id='".$random_userid."'"); if(mysql_num_rows($sql)==0) { $insert=mysql_query("insert into users (user_id) values ('".$random_userid."')"); } ?> If user id not exists in database, that user id inserting in database successfully. If not, empty value is inserting, not generating new user id. Can any one help me out please. Similar TutorialsPlease i'm working on a project and i need to write a code that generates a unique random serial number.How can i go about it? Here is my code if(isset($_POST['pass_btn'])) { $numchars = 8; $chars = explode(',','2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,2,3,4,5,6,7,8,9'); $password=''; for($i=0; $i<$numchars;$i++) { $password.=$chars[rand(0,count($chars)-1)]; } } This is set up so when a person pressing the pass_btn, a password is provided. This works just fine. However, it refreshes the page and clears all other data that user may have entered. Suggestions? Hi, I have a trouble figuring out how to properly convert a list of product data from XML into CSV format. My source is a XML file containing a list of products with attributes like color, size, material etc. with the following structu Code: [Select] <?xml version="1.0" encoding="utf-8" ?> <store> <products> <product> <name>T-Shirt</name> <price>19.00</price> <attributes> <attribute> <name>Color</name> <options> <option> <name>White</name> <price>0.00</price> </option> <option> <name>Black</name> <price>0.00</price> </option> <option> <name>Blue</name> <price>0.00</price> </option> </options> </attribute> <attribute> <name>Size</name> <options> <option> <name>XS</name> <price>-5.00</price> </option> <option> <name>S</name> <price>-5.00</price> </option> <option> <name>M</name> <price>0.00</price> </option> <option> <name>L</name> <price>0.00</price> </option> <option> <name>XL</name> <price>5.00</price> </option> </options> </attribute> </attributes> </product> <product> <name>Sweatshirt</name> <price>49.00</price> <attributes> <attribute> <name>Color</name> <options> <option> <name>White</name> <price>0.00</price> </option> <option> <name>Black</name> <price>0.00</price> </option> </options> </attribute> <attribute> <name>Size</name> <options> <option> <name>XS</name> <price>-10.00</price> </option> <option> <name>M</name> <price>0.00</price> </option> <option> <name>XL</name> <price>10.00</price> </option> </options> </attribute> <attribute> <name>Material</name> <options> <option> <name>Cotton</name> <price>10.00</price> </option> <option> <name>Polyester</name> <price>0.00</price> </option> </options> </attribute> </attributes> </product> <product> <name>Earrings</name> <price>29.00</price> </product> </products> </store> Each product has a number of elements like name, price etc. but also a random number of attributes (like color, size, material etc.) that also have a random number of options. Each option can affect the price of the product, so ordering a XS sized t-shirt can be cheaper than ordering a XL sized t-shirt. I would like to end up with a CSV representing one attribute combination on each line. In my example that would result in 3 colors x 5 sizes = 15 lines for the T-Shirt , 2 colors x 3 sizes x 2 materials = 12 lines for the Sweatshirt and 1 line for the Earrings without any attributes: Code: [Select] name,price,color,size,material T-Shirt,14.00,White,XS, T-Shirt,14.00,Black,XS, T-Shirt,14.00,Blue,XS, T-Shirt,14.00,White,S, T-Shirt,14.00,Black,S, T-Shirt,14.00,Blue,S, T-Shirt,19.00,White,M, T-Shirt,19.00,Black,M, T-Shirt,19.00,Blue,M, T-Shirt,19.00,White,L, T-Shirt,19.00,Black,L, T-Shirt,19.00,Blue,L, T-Shirt,24.00,White,XL, T-Shirt,24.00,Black,XL, T-Shirt,24.00,Blue,XL, Sweatshirt,49.00,White,XS,Cotton Sweatshirt,49.00,Black,XS,Cotton Sweatshirt,59.00,White,M,Cotton Sweatshirt,69.00,Black,M,Cotton Sweatshirt,69.00,White,XL,Cotton Sweatshirt,69.00,Black,XL,Cotton Sweatshirt,39.00,White,XS,Polyester Sweatshirt,39.00,Black,XS,Polyester Sweatshirt,49.00,White,M,Polyester Sweatshirt,49.00,Black,M,Polyester Sweatshirt,59.00,White,XL,Polyester Sweatshirt,59.00,Black,XL,Polyester Earrings,29.00,,, I already managed to generate the CSV Output for simple products like the Earrings and products with just one attribute, but am struggling to come up with a way to generate all possible product attribute combinations for products with more than one attribute. My miserable attempts at this so far have produced following code: Code: [Select] <?php mb_internal_encoding("UTF-8"); header('Content-Type: text/html; charset=utf-8'); $source = "example.xml"; $handle = fopen($source, "r"); $fp = fopen('export.csv', 'w'); $xml = simplexml_load_file($source); // Generate list of attributes (for csv header etc.) $header_attributes = array(); foreach ($xml->products->product as $product) { if(isset($product->attributes)) { foreach($product->attributes->attribute as $attribute) { array_push($header_attributes, $attribute->name); } } } $header_attributes = array_unique($header_attributes); $csvheader = array( 'name','price' // these exist for all products, could also include weight, image, description, special price etc... ); $static_csvheadercount = count($csvheader); foreach($header_attributes as $attribute) { array_push($csvheader, $attribute); // add variable number of attribute fields to csv header } fputcsv($fp, $csvheader); foreach ($xml->products->product as $product) { // loop through each product if(isset($product->attributes)) $simple = 0; else $simple = 1; if($simple == 1) { // if product is a simple product with no attributes $output=array(); array_push($output,(string)$product->name); array_push($output,(string)$product->price); for($i = $static_csvheadercount + $attribute_position; $i < count($csvheader); $i++) { array_push($output, ''); } fputcsv($fp, $output); } else { // is a configurable product with attributes $json = json_encode($product->attributes); $attributes = json_decode($json, TRUE); $attributes_number = count($product->attributes->attribute); if($attributes_number > 1) { // if product has more than 1 attributes so we have to generate each attribute combination // // I'm trying to figure out what should happen here // } else { // if product has only one attribute $attributename = (string)$product->attributes->attribute->name; $attribute_position = array_search($attributename, $header_attributes); $options_number = count($product->attributes->options->option); $pos = 1; foreach($attributes['attribute']['options']['option'] as $option) { $output=array(); array_push($output,(string)$product->name); array_push($output,(string)$product->price); for($i = $static_csvheadercount - 1; $i < ($static_csvheadercount + $attribute_position); $i++) { array_push($output, ''); } $output[$static_csvheadercount + $attribute_position] = $option['name']; for($i = $static_csvheadercount + $attribute_position; $i < count($csvheader) - 1 ; $i++) { array_push($output, ''); } fputcsv($fp, $output); $pos++; } $output=array(); array_push($output,(string)$product->name); array_push($output,(string)$product->price); for($i = $static_csvheadercount; $i < count($csvheader); $i++) { array_push($output, ''); } fputcsv($fp, $output); } } } ?> I've been stuck at this problem for hours unable to figure out a solution. Can someone give a few tips or pointer how to achieve the output for products with multiple attributes? I need a way to generate a random number and insert into a database, and I need the database to not contain any duplicates of that number. I basically need to generate a RMA # (Return Merchandise Authorization Number), so the numbers absolutely CAN NOT be duplicate. I have no ideas how to go about this. Should I generate a random number, search the database and see if there's a duplicate, and if there is re-run the script? So if I change the user his data to banned or something he don't change Here is the part of the code: Code: [Select] $userInfo = $db->getuserInfo($_GET['id']); if ($userInfo) { echo '<form action="'.coreLink('admin', 'users').'" method="post"><input type="hidden" name="userID" value="'.$userInfo['ID'].'"><ul class="inputs"> <li> <div style="float:right"><input type="text" name="username" class="input" value="'.$userInfo['username'].'"></div> '.__('Username').'<br /><small>'.__('Nickname of the user').'</small> </li> <li> <div style="float:right"><input type="text" name="pass" class="input" value=""></div> '.__('Change password').'<br /><small>'.__("Fill this input if you want to change it's password").'</small> </li> <li> <div style="float:right"><input type="text" name="email" class="input" value="'.$userInfo['email'].'"></div> '.__('Email').'<br /><small>'.__('Email of the user').'</small> </li> <li> <div style="float:right"><input type="text" name="api" class="input" value="'.$userInfo['api'].'"></div> '.__('API Code').'<br /><small>'.__('Used to access through the API').'</small> </li> <li> <div style="float:right"><select class="input" name="status" style="width:311px">'; foreach (array('ok'=>__('Active'), 'nc'=>__('Not confirmed'), 'banned'=>__('Banned')) as $key=>$long) { echo '<option value="'.$key.'"'; if ($key == $userInfo['status']) echo ' selected'; echo '>'.$long.'</option>'; } echo '</select> </div> '.__('Status').'<br /><small>'.__('It can be active, banned..').'</small> </li> <li> <fieldset id="shorters" style="border: 1px solid #ddd;-moz-border-radius:2px;-webkit-border-radius:2px"><legend>'.__('Profile').'</legend><br /><div style="padding-left:40px;margin-bottom:20px;width:110px">'; $avatar = getAvatar($userInfo['ID'], '48'); if (!$userInfo['gravatar'] && ($avatar != $jk->base."static/img/avatar/default_note.png")) echo '<div style="float:right;font-size:.8em"><input type="checkbox" name="avatar"> <img src="'.$jk->base.'static/img/trash.gif"></div>'; echo '<img src="'.getAvatar($userInfo['ID'], '48').'" style="border: 1px solid #ddd"></div> <ul> <li> <div style="float:right"><input type="text" name="profile_name" class="input" value="'.$userInfo['realname'].'"></div> '.__('Name').'<br /><small>'.__('Real name of the user').'</small> </li> <li> <div style="float:right"><input type="text" name="profile_web" class="input" value="'.$userInfo['profile']['url'].'"></div> '.__('Website').'<br /><small>'.__('Website of the user').'</small> </li> <li> <div style="float:right"><input type="text" name="profile_location" class="input" value="'.$userInfo['location'].'"></div> '.__('Location').'<br /><small>'.__('Location of the user').'</small> </li> <li> <div style="float:right"><input type="text" name="profile_bio" class="input" value="'.$userInfo['profile']['bio'].'"></div> '.__('Bio').'<br /><small>'.__('Description of the user').'</small> </li> </ul></fieldset> </li> <li> <div style="float:right"><select class="input" name="language" style="width:311px">'; foreach (return_languages() as $short=>$lang) { echo '<option value="'.$short.'"'; if ($short == $userInfo['language']) echo ' selected'; echo '>'.$lang.'</option>'; } echo '</select> </div> '.__('Language').'<br /><small>'.__('Language of the user').'</small> </li> <li> <div style="float:right"><select class="input" name="theme" style="width:311px">'; foreach ($jk->allowed_themes as $theme) { echo '<option value="'.$theme.'"'; if ($theme == $userInfo['theme']) echo ' selected'; echo '>'.$theme.'</option>'; } echo '</select> </div> '.__('Theme').'<br /><small>'.__('Skin of Jisko').'</small> </li> <li> <div style="float:right"><input type="text" name="invitations" class="input" value="'.$userInfo['invitations'].'"></div> '.__('Number of invitations').'<br /><small>'.__('Number of invitations that the user has').'</small> </li> <li> <div style="float:right"><input type="text" name="openid" class="input" value="'.$userInfo['openid'].'"></div> '.__('OpenID').'<br /><small>'.__('Used to access Jisko trough an OpenID account').'</small> </li> <li> <div style="float:right"><input type="text" name="facebook" class="input" value="'.$userInfo['facebook'].'"></div> '.__('Facebook ID').'<br /><small>'.__('Used to access Jisko trough a Facebook account').'</small> </li> </ul> <br /><input type="submit" value="'.__('Save').'"><br /><br /></form>'; } else header('Location: '.coreLink('admin', 'users')); } I am creating a drink recipe site. So far I have created the mysql table and the page where i can enter in the drink name ingredients ect. and it inserts into the table. Could some one point me in the right direction where when I make an entry into this table a new page is created from the content. How would I go about doing this? Hi all, I want to create an array from the output of a table. In the table cell I have some numbers where for each number I would like to relate it to a value in another table. However using the code below I get Array ( => "26","27","28","29","30","31" ) from the print_r($arr); meaning that $range ins't being treated as an array, and hence, the second query only gives one value. Code: [Select] $showIng = mysql_query("SELECT * FROM recipe WHERE name = '$dish'") or die(mysql_error()); $rowShowIng = mysql_fetch_assoc($showIng); $range = $rowShowIng['keyno']; $arr = array($range); print_r($arr); foreach ($arr as &$value) { $getIng = mysql_query("SELECT * FROM keywords WHERE keyid = '$value'") or die(mysql_error()); $rowGetIng = mysql_fetch_assoc($getIng); echo $rowGetIng['ingredient']; } So, I want to know how I can create the array from $range Thanks Hey all.. I'm trying to pick up PHP by reading ebooks and follow tutorials. I am now busy with creating a thumbnailgallery from uploaded pics per user. I want to let the visitor scroll through a row of thumbnails by clicking next or previous. There are 3 different rows of thumbnails. Here's how it looks like: <<previous (row1 of 6thumbnails) next>> <<previous (row2 of 6thumbnails) next>> <<previous (row3..... ) next>> when page loads mysql fetches rows of information for the filenames...then there is a foreach row loop that does first a do ..while loop to build up the thumbnailrows...and then creates the navigation links previous and next who send the "page"+1 or "page"-1 to _GET array so that the thumbnail 7 until 12 will be shown. The problem i run into is that i want the main code page to remember at which "page" of scrolling through the thumnails he is. Now it is that when a user scrolls one row of thumbnails and stops at the 3rd "page" of it and then clicks on a different row to go to "page" 2 of that row that all the rows jump together back to "page" 1. I thought there may be a solution in storing the number of row and the number of page into an array but can't seem to find a solution.... Has anybody got experience in this? Help would be very welcome i'm totally stuck and cant read about it in tutorials/ebooks.... greets from holland.. GJ Hi, I'm trying to make a dynamic html table to contain the mysql data that is generated via php. I'm trying to display a user's friends in a table of two columns and however many rows, but can't seem to figure out what is needed to make this work. Here's my code as it stands: Code: [Select] <?php //Begin mysql query $sql = "SELECT * FROM friends WHERE username = '{$_GET['username']}' AND status = 'Active' ORDER BY friends_with ASC"; $result = mysql_query($sql); $count = mysql_num_rows($result); $sql_2 = "SELECT * FROM friends WHERE friends_with = '{$_GET['username']}' AND status = 'Active' ORDER BY username ASC"; $result_2 = mysql_query($sql_2); $count_2 = mysql_num_rows($result_2); while ($row = mysql_fetch_array($result)) { echo $row["friendswith"] . "<br>"; } while ($row_2 = mysql_fetch_array($result_2)) { echo $row_2["username"] . "<br>"; } ?> The above simply outputs all records of a user's friends (their usernames) in alphabetical order. The question of how I'd generate a new row each time a certain amount of columns have been met, however, is beyond me. Anyone know of any helpful resources that may solve my problem? Thanks in advance =) Hi, I am getting frustrated beyond belief at the moment with trying to get a very simple script to run, I am using PHP 5.3.3 and MySQL 5.1 on a Win2k8 server with IIS7.5. Basically my script is connecting to a local database, running a single select query, returning those rows and building up a string from them. The problem is that I am receiving complete BS responses from PHP that the access is denied for the user being specified. This is complete rubbish since the user can connect via mysql, sqlyog, ASP.NET MVC without issue but for some bizarre reason it is not working via PHP. The code for the script is here : Code: [Select] <?php $mysql = mysql_connect('127.0.0.1:3306', 'myuser', 'mypass', 'mydatabase'); if (!$mysql) { die(mysql_error()); $content = "<nobr></nobr>"; } else { $result = mysql_query('SELECT * FROM tblEventGroup'); $content = "<nobr>"; if ($result) { while($row = mysql_fetch_assoc($result)) { $content .= "<span>"; $content .= $row['GroupName']; $content .= "</span>"; $content .= "<a href=\"../Event/EventSearch?groupid="; $content .= $row['GroupId']; $content .= "\" target=\"_blank\">Book here</a> "; } } mysql_close($mysql); $content .= "</nobr>"; } ?> I cannot for the life of me understand what the problem is, the return error is Access denied for user 'myuser'@'localhost' (using password: YES) I am having trouble trying to save my image file names to mysql after reading a dir. I am trying to use the file below.
Any help would be appreciated. I was originallly getting the files to list but they we not showing up in the database.
Now the page shows up blank.
<?php require("config_0.php"); // Connect to server and select database. mysql_connect($dbhost, $dbuser, $dbpass)or die("cannot connect"); mysql_select_db("test")or die("cannot select DB"); $files = glob("images/*.jpg"); for ($i=1; $i<count($files); $i++) { $num = $files[$i]; $sql="INSERT INTO images (url) VALUES ('$num')"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } echo '<img src="'.$num.'" alt="random image">'." "; } ?>
Hello, I am a newbie regarding PHP and have done mostly only front-end web design for a couple of years and recently started querying DB's and displaying the data, but now this is a new project.
I've tested code snippets as the ones below, but fail to incorporate them in the bigger picture of what I'm trying to achieve. <?php // https://gist.github.com/magnetikonline/650e30e485c0f91f2f40 class DumpHTTPRequestToFile { public function execute($targetFile) { $data = sprintf( "%s %s %s\n\nHTTP headers:\n", $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL'] ); foreach ($this->getHeaderList() as $name => $value) { $data .= $name . ': ' . $value . "\n"; } $data .= "\nRequest body:\n"; file_put_contents( $targetFile, $data . file_get_contents('php://input') . "\n" ); echo("Done!\n\n"); } private function getHeaderList() { $headerList = []; foreach ($_SERVER as $name => $value) { if (preg_match('/^HTTP_/',$name)) { // convert HTTP_HEADER_NAME to Header-Name $name = strtr(substr($name,5),'_',' '); $name = ucwords(strtolower($name)); $name = strtr($name,' ','-'); // add to list $headerList[$name] = $value; } } return $headerList; } } (new DumpHTTPRequestToFile)->execute('./dumprequest.csv'); This snippet also seems to return the headers and their values but I don't know how to efficiently write and append it to a TXT or CSV, or preferably, directly into a MySQL database. <?php foreach (getallheaders() as $name => $value) { echo "$name: $value"; echo "<br>"; } ?>
Any help towards storing the header values of HTTP POST requests into a database would be greatly appreciated! I receive files/images and loop through an array as follows:
$files=rearrfiles( $_FILES['image']); foreach($files as $key=>$item) { if(is_array($item) && !empty($item['name']) && !empty($item['tmp_name'])){ //$_POST['imageFile']=$item['name']; //echo $item['name']; if($error!=true && !uploadImageB(array('image'=>'image'), DB_EXTENTION."mod_projects_images", $naming, $search = $editId, $dir, 'photo')) { $error=true; $action='Edit'; $message.='<br>Images were unable to be uploaded.'; } } }The function uploadImageB() is as follows: function uploadImageB($info, $table, $naming, $search, $path, $add='uploaded', $maxw=1280, $maxh=1280, $dynamic=true, $id='Id', $thumbMaxWidth = 120) { global $connection; if(!$_POST){ global $HTTP_POST_VARS; @$_POST=$HTTP_POST_VARS;} if(!$_FILES){ global $HTTP_POST_FILES; @$_FILES=$HTTP_POST_FILES;} if(is_array($info) && !empty($info) && $table!='' && !empty($path)) { $error=false; $d=$naming; foreach($info as $key=>$val) { $names[$val]=$dynamic==true?$add.'_'.$result[$id].'_'.$d.'_.'.strtolower(mygetext($_FILES[$val]['name'])):$add.strtolower(mygetext($_FILES[$val]['name'])); if(is_array(@$_FILES[$val]) && !empty($_FILES[$val]['name']) && !empty($names[$val])) { if(!singMove($path, $names[$val], $_FILES[$val], array(), array('gif', 'jpeg', 'jpg', 'png', 'bmp', 'svg'))) { $error=true; break; } else{ $valid[$val]=$names[$val]; resizeImage($path.$names[$val], $maxw, $maxh); make_thumb($path.$names[$val],$names[$val], $path, $thumbMaxWidth); } } } if($error==true) return false; elseif(!empty($valid)) { $connection->info=$info; $connection->input=$valid; $connection->id=array('field'=>$id, 'val'=>addslashes($result[$id])); $connection->makenew($table); $connection->return_db($connection->query); } } return true; }I get the error: Images were unable to be uploaded. Any help? In MVC type architecture, is it safe to do this ini_set("mysql.default_host"$mysql_host); ini_set("mysql.default_user",$mysql_user); ini_set("mysql.default_password",$mysql_pass); in my index.php file. Then, every time time I do a query in a model, mysql_connect(); // MySQL connects using the default values from the ini_sets we did. mysql_query($query); mysql_close(); The reason behind this, would be to avoid passing database variables to objects/models etc or defining constants. Maybe there's a better way? I'm looking into database abstraction. Hi Guys, I have stuck with my problem and i am nothing to php, i already posted this to another php script forum, but haven't solve, so i wondering if anyone here help me and many thanks. this is all about game scores from .xml file inside the xml file itself as: Code: [Select] <gesmes:Envelope> <gesmes:subject>Reference Scores</gesmes:subject> - <gesmes:Sender> <gesmes:name>Game Information Scores</gesmes:name> </gesmes:Sender> - <Cube> - <Cube time="2010-10-13"> <Cube scores="GameA1" value="1.5803"/> <Cube scores="GameA2" value="21.35"/> ............etc <Cube scores="GameA15" value="135"/> </Cube> </Cube> </gesmes:Envelope> then i got php script that can save all data of .xml above to mysql, look like <?php class Scores_Converter { var $xml_file = "http://192.168.1.112/gamescores/scores-daily.xml"; var $mysql_host, $mysql_user, $mysql_pass, $mysql_db, $mysql_table; var $scores_values = array(); //Load convertion scores function Scores_Converter($host,$user,$pass,$db,$tb) { $this->mysql_host = $host; $this->mysql_user = $user; $this->mysql_pass = $pass; $this->mysql_db = $db; $this->mysql_table = $tb; $this->checkLastUpdated(); $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); $rs = mysql_select_db($this->mysql_db,$conn); $sql = "SELECT * FROM ".$this->mysql_table; $rs = mysql_query($sql,$conn); while($row = mysql_fetch_array($rs)) { $this->scores_values[$row['scores']] = $row['value']; } } /* Perform the actual conversion, defaults to 1.00 GameA1 to GameA3 */ function convert($amount=1,$from="GameA1",$to="GameA3",$decimals=2) { return(number_format(($amount/$this->scores_values[$from])*$this->scores_values[$to],$decimals)); } /* Check to see how long since the data was last updated */ function checkLastUpdated() { $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); $rs = mysql_select_db($this->mysql_db,$conn); $sql = "SHOW TABLE STATUS FROM ".$this->mysql_db." LIKE '".$this->mysql_table."'"; $rs = mysql_query($sql,$conn); if(mysql_num_rows($rs) == 0 ) { $this->createTable(); } else { $row = mysql_fetch_array($rs); if(time() > (strtotime($row["Update_time"])+(12*60*60)) ) { $this->downloadValueScores(); } } } /* Download xml file, extract exchange values and store values in database */ function downloadValueScores() { $scores_domain = substr($this->xml_file,0,strpos($this->xml_file,"/")); $scores_file = substr($this->xml_file,strpos($this->xml_file,"/")); $fp = @fsockopen($scores_domain, 80, $errno, $errstr, 10); if($fp) { $out = "GET ".$scores_file." HTTP/1.1\r\n"; $out .= "Host: ".$scores_domain."\r\n"; $out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { $buffer .= fgets($fp, 128); } fclose($fp); $pattern = "{<Cube\s*scores='(\w*)'\s*value='([\d\.]*)'/>}is"; preg_match_all($pattern,$buffer,$xml_values); array_shift($xml_values); for($i=0;$i<count($xml_values[0]);$i++) { $exchange_value[$xml_values[0][$i]] = $xml_values[1][$i]; } $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); $rs = mysql_select_db($this->mysql_db,$conn); foreach($exchange_value as $scores=>$value) { if((is_numeric($value)) && ($value != 0)) { $sql = "SELECT * FROM ".$this->mysql_table." WHERE scores='".$scores."'"; $rs = mysql_query($sql,$conn) or die(mysql_error()); if(mysql_num_rows($rs) > 0) { $sql = "UPDATE ".$this->mysql_table." SET value=".$value." WHERE scores='".$scores."'"; } else { $sql = "INSERT INTO ".$this->mysql_table." VALUES('".$scores."',".$value.")"; } $rs = mysql_query($sql,$conn) or die(mysql_error()); } } } } /* Create the scores table */ function createTable() { $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass); $rs = mysql_select_db($this->mysql_db,$conn); $sql = "CREATE TABLE ".$this->mysql_table." ( scores char(3) NOT NULL default '', value float NOT NULL default '0', PRIMARY KEY(scores) ) ENGINE=MyISAM"; $rs = mysql_query($sql,$conn) or die(mysql_error()); $sql = "INSERT INTO ".$this->mysql_table." VALUES('GameA0',1)"; $rs = mysql_query($sql,$conn) or die(mysql_error()); $this->downloadValueScores(); } } ?> but that php script above just create table of mysql below CREATE TABLE IF NOT EXISTS `scrore_table` ( `scores` char(3) NOT NULL default '', `value` float NOT NULL default '0', PRIMARY KEY (`scores`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; INSERT INTO `scrore_table` (`scores`, `value`) VALUES ('GameA0', 1), ('GameA1', 1.5651), ......etc ('GameA15', 95.572); while of my existing database table look like: CREATE TABLE IF NOT EXISTS `scrore_table` ( `scrore_id` int(11) NOT NULL auto_increment, `scrore_title` varchar(32) collate utf8_bin NOT NULL default '', `scores` varchar(3) collate utf8_bin NOT NULL default '', `decimal_place` char(1) collate utf8_bin NOT NULL, `value` float(15,8) NOT NULL, `date_updated` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`currency_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; ; INSERT INTO `scrore_table` (`scrore_id`, `scrore_title`, `scores`, `decimal_place`, `value`, `date_updated`) VALUES (1, 'Game Class A0', 'GameA0', '2', 1.00000000, '2010-04-06 22:00:54'), (2, 'Game Class A1', 'GameA1', '2', 1.52600002, '2010-04-06 22:00:54'), ..............................etc (14, 'Game Class A15', 'GameA15', '2', 1.13999999, '2010-04-06 22:00:54'); as i said i newbie to php then i dont know how to modify the php code above able to automatically create the table and insert/update new fields e.g. scrore_id, scrore_title,decimal_place, date_updated also all values to my existing database i looking for some helps and thanks in advance.. <?php $GLOBALS['title']="Admission-HMS"; $base_url="http://localhost/hms/"; require('./../../inc/sessionManager.php'); require('./../../inc/dbPlayer.php'); require('./../../inc/fileUploader.php'); require('./../../inc/handyCam.php'); $ses = new \sessionManager\sessionManager(); $ses->start(); if($ses->isExpired()) { header( 'Location:'.$base_url.'login.php'); } else { $name=$ses->Get("loginId"); } $msg=""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_POST["btnSave"])) { $db = new \dbPlayer\dbPlayer(); $msg = $db->open(); echo '<script type="text/javascript"> alert("'.$msg.'");</script>'; if ($msg = "true") { $userIds = $db->getAutoId("U"); $flup = new fileUploader\fileUploader(); $perPhoto = $flup->upload("/hms/files/photos/",$_FILES['perPhoto'], $userIds[1]); // var_dump($perPhoto); $handyCam=new \handyCam\handyCam(); if (strpos($perPhoto, 'Error:') === false) { $dateNow=date("Y-m-d"); $data = array( 'userId' => $userIds[1], 'userGroupId' => "UG004", 'name' => $_POST['name'], 'studentId' => $_POST['stdId'], 'cellNo' => $_POST['cellNo'], 'gender' => $_POST['gender'], 'dob' => $handyCam->parseAppDate($_POST['dob']), 'passportNo' => $_POST['passportNo'], 'fatherName' => $_POST['fatherName'], 'fatherCellNo' => $_POST['fatherCellNo'], 'perPhoto' => $perPhoto, 'admitDate' => $dateNow, 'isActive' => 'Y' ); $result = $db->insertData("studentinfo",$data); if($result>=0) { $data = array( 'userId' => $userIds[1], 'userGroupId' => "UG004", 'name' => $_POST['name'], 'loginId' => $_POST['stdId'], 'verifyCode' => "vhms2115", 'expireDate' => "2115-01-4", 'isVerifed' => 'Y' ); $result=$db->insertData("users",$data); if($result>0) { $id =intval($userIds[0])+1; $query="UPDATE auto_id set number=".$id." where prefix='U';"; $result=$db->update($query); // $db->close(); echo '<script type="text/javascript"> alert("Admitted Successfully.");</script>'; } else { echo '<script type="text/javascript"> alert("' . $result . '");</script>'; } } elseif(strpos($result,'Duplicate') !== false) { echo '<script type="text/javascript"> alert("Student Already Exits!");</script>'; } else { echo '<script type="text/javascript"> alert("' . $result . '");</script>'; } } else { echo '<script type="text/javascript"> alert("' . $perPhoto . '");</script>'; } } else { echo '<script type="text/javascript"> alert("' . $msg . '");</script>'; } } I would like to store PDF file into mysql (this part works) and then send it as email attachment and it should be retrieved from mysql table. Here's the code I have for now, but what it gives me is 0bytes large PDF file Saving PDF to mysql (it works), because size of blob in mysql table is OK. $fp = fopen('generated.pdf', 'r'); $content = fread($fp,filesize('generated.pdf')); $content = addslashes($content); fclose($fp); $DB->Query('insert into pdf_files (pdf_file, name) values ("'.$content.'", "'.$name.'")'); And here's the mailing part <?php $query = "SELECT name, pdf_file FROM pdf_files $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array ( $result)) { $fileContent =$row['pdf_file']; $fileName=$row['name']; } $fileatt = $fileContent; // getting file $fileatt_type ="application/pdf"; //type of file $fileatt_name = "attachment.pdf"; // name $fileatt_size = $fileSize; $email_from = "dont@have.it"; // mail from $email_subject = "Testtt"; // subject $email_message = "Testtt.<br>"; $email_message .= "Testtt.<br>"; // Message $email_to = $mail_user; // users mail $headers = "From: ".$email_from; $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; $email_message .= "Testtt.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n"; $data = chunk_split(base64_encode($data)); $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . //"Content-Disposition: attachment;\n" . //" filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data .= "\n\n" . "--{$mime_boundary}--\n"; $ok = @mail($email_to, $email_subject, $email_message, $headers); if($ok) { echo "<font face=verdana size=2><center>Mail was sent</center>"; } else { die("Error!"); } ?> create table mimi (mimiId int(11) not null, mimiBody varchar(255) ); <?php //connecting to database include_once ('conn.php'); $sql ="SELECT mimiId, mimiBody FROM mimi"; $result = mysqli_query($conn, $sql ); $mimi = mysqli_fetch_assoc($result); $mimiId ='<span>No: '.$mimi['mimiId'].'</span>'; $mimiBody ='<p class="leading text-justify">'.$mimi['mimiBody'].'</p>'; ?> //what is next? i want to download pdf or text document after clicking button or link how to do that Is there anyway in MySQL you can select a random record in a table? I normally do this by generating a random number first and then using that number to find a record but was wondering if there is an easier way. Thanks for any help. How would I make it so that for every set of data where a fieldname is 1+ it picks a random one out. For example User Hit Luke 0 Peter 1 Alex 3 Peter 1 For every value where Hit is 1 or over it selects out of the query results a random username. |