PHP - Give Unique Values Inside Dynamiclist
Similar TutorialsI want to create an application for sending mails using PHPMailer by placing it on my website server (using SMTP), but I can not get object of class phpmailer to change its properties of: to_name to_email ContentType from default (i.e. null). Why are the properties keeping default values from the PHPMailer class, and not accepting my once, though I check values i get from DB and they are good. ContentType is set in a config file. Here is part of var_dump ($mailer); object of my extended class: object(MyMailer)#2 (56) { ["priority"]=> int(3) ["to_name"]=> NULL ["to_email"]=> NULL ... ["ContentType"]=> string(10) "text/plain"... also I get value of ["Port"]=> int(26) but ["SMTP_PORT"]=> int(25). I need to use smtp port 26. And here is the extended class of phpmailer require_once './PHPMailer/class.phpmailer.php'; require_once 'mailer-config.php'; class MyMailer extends PHPMailer { var $priority = 3; var $to_name = null; var $to_email = null; var $From = null; var $FromName = null; var $Sender = null; var $ContentType = null; function MyMailer() { global $eSlanje; // Comes from mailer-config.php $eSlanje array if($eSlanje['smtp_mode'] == 'enabled') { $this->Host = $eSlanje['smtp_host']; $this->Port = $eSlanje['smtp_port']; if($eSlanje['smtp_username'] != '') { $this->SMTPAuth = true; $this->Username = $eSlanje['smtp_username']; $this->Password = $eSlanje['smtp_password']; } $this->Mailer = "smtp"; } if(!$this->From) { $this->From = $eSlanje['from_email']; } if(!$this->FromName) { $this->FromName = $eSlanje['from_name']; } if(!$this->Sender) { $this->Sender = $eSlanje['from_email']; } $this->Priority = $this->priority; //echo "<br>eSlanje[content_type]"; //var_dump ($eSlanje['content_type']); $this->ContentType = $eSlanje['content_type']; } } and here is the cofig file: mailer-config.php <?php $eSlanje['from_email'] = "hi@mysite.com"; $eSlanje['from_name'] = "Joe Blog"; $eSlanje['title'] = "hi there"; $eSlanje['content_type'] ="text/html"; $eSlanje['smtp_username'] = null; $eSlanje['smtp_mode'] = "enabled"; $eSlanje['smtp_port'] = 26; $eSlanje['smtp_host'] = "mail.mysite.com"; Here is where I insert values of email and name into the object: <?php session_start(); include ("password.php"); require_once 'class_lib/MyMailer.php'; require "class_lib/MySQL_Database.php"; require "get_email_template.php"; $db = new MySQL_Database (); $id = isset($_GET['id']) ? $_GET['id'] : false; $sql = "select email,ime from ".TABLE." where id = $id"; $query = mysql_query ($sql); $toClient = mysql_fetch_array($query); $to = isset($toClient['email']) ? $toClient['email'] : false; var_dump($to); // here I get a valid email address $to_name = isset($toClient['ime']) ? $toClient['ime'] : false; //var_dump($to_name); // here I get a valid preson's name $mailer = new MyMailer(); $mailer->AddAddress($to, $to_name); $mailer->Body = get_htmlBody(); $mailer->AltBody = get_txtBody(); if(!$mailer->Send()) { echo "<br> Mailer Error: " . $mailer->ErrorInfo." "; } else { echo "<br>message not sent  "; } $mailer->ClearAddresses(); var_dump($mailer); // this is where the object trace comes from ?> I have a Unique Constraint setup on (emailAddress and pin) to allow multiple email addresses be the same and multiple pins but not the same emailAddress and pin value together (unique(emailAddress, pin)) Anyway, I am trying to generate a pin through a random seed, but I can't get my code to work properly to test if the combination already exists. Here is the chunk that does not work: Code: [Select] $tries = 0; $foundRows=0; do { $pin=null; $tries++; $pin = str_pad(rand(0,9), 4, "0", STR_PAD_LEFT); $stmt = $dbh->prepare("SELECT COUNT(*) FROM ajax WHERE emailAddress=:email AND pin=:pin LIMIT 1"); if ($stmt->bindParam(':email', $email, PDO::PARAM_STR) && $stmt->bindParam(':pin', $pin, PDO::PARAM_INT)) { $stmt->execute(); $foundRows = $dbh->query("SELECT FOUND_ROWS()")->fetchColumn(); echo "<br />$foundRows<br />"; } else { die ("<p>Could not bind to data verification</p>"); } } while ($foundRows > 0); This is always returning $foundRows=0 so always exiting the loop, and giving me a constraint error. Any ideas? Maybe a better way to do this? I have a simple db with values. I want to find all duplicate values and rename them 1,2,3 - so if I have these values for a 'colour' field: pID / color 1 / brown 2 / blue 3 / red 4 / red 5 / brown ...would result in: 1 / brown1 2 / blue 3 / red1 4 / red2 5 / brown2 ...is this possible? Hi I am new this forum and looking for some much appreciated help with something that has me stumped. I have extracted regions from image names in a directory. example: 'edinburgh_castle_(Edinburgh).jpg' (Extracted Edinburgh from in-between the brackets) So I have a list of Regions, extracted from all the various image names in the directory which I want to populate into a dynamic drop down menu for filtering purposes. Here's my issue... I want there to be only one 'Edinburgh' option appearing in my drop down menu. I don't want duplicates. Here is my code so far. php: [Select] Hello All, I have a contact directory database. It has all the employees of my company (name, phone, email, department, building, etc). Say on one page I have the Marketing Department, and I want to say: "The Marketing Department Director is ________" How would I assign that value from the database? Do I want to put in a unique "keyword" field in the database, but then how would I store all the values automatically on the page? I see pages where I would want to list the Marketing Director, and his secretary, then another page with the Sales Director, and his secretary, etc.... all with being able to change the values in the database, and it changing across all the pages instantly. Do I need to say on every page "select * from database where keyword = marketingdirector" and then store that result as a variable? It seems unpractical to repeat that a few times for each different person I want to list. Is there a better way to do this then I'm thinking? Thanks all! Hi all, I have a situation where I need to remember what check boxes where checked over pagination, I have managed to do this via the use of this: http://jamesfunk.com/wordpress/?p=65 The problem is that as the code stood: Code: [Select] <input type="checkbox" name="compare" value="<?php echo $list['jobseeker_id'];?>" class="remember_cb"/> It was treating one ticked checkbox as them all because they all have the same name and are in the a while loop! I countered this by changing the code to: Code: [Select] <input type="checkbox" name="compare<?php echo $list['jobseeker_id']?>" value="<?php echo $list['jobseeker_id'];?>" class="remember_cb"/> Which effectively now makes the checkbox name unique... i.e. compare{id}. The problem with this is that I can now no longer process it. This is my processing code: $jobseekers = $_POST['compare']; $i = 0; for($i; $i<count($jobseekers); $i++){ $query = "SELECT * FROM jobseekers WHERE jobseeker_id = '$jobseekers[$i]'"; $result = mysql_query($query) or die (mysql_error()); while ($row = mysql_fetch_array($result)) { // Spit out the required data } } As you can see I am trying to get the data from $_POST['compare'], which will obviously now be blank as I have had to make the name unique.... the trouble is I'm not sure how to actually process this. Can anyone help me out here? any help or advice would be greatly appreciated! many thanks, Greens85 Hello, I need some help. Say that I have a list in my MySQL database that contains elements "A", "S", "C", "D" etc... Now, I want to generate an html table where these elements should be distributed in a random and unique way while leaving some entries of the table empty, see the picture below. But, I have no clue how to do this... Any hints? Thanks in advance, Vero 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.. I have table which has a data so_month: FromMonth : 5 ToMonth : 7 and I have table working_days: MonthName May Jun Jul MonthNumber 05 06 07 WorkingDays 23 24 23 Now I have function to get the 3 consecutive months from FromMonth to ToMonth , which as you can see from May to Jul Now I have problem in getting the SUM of Working days. here is my code: <?php $sql = "SELECT FromMonth, ToMonth FROM so_month"; $res = mysql_query($sql,$con); $row = mysql_fetch_assoc($res); $FromMonth = $row['FromMonth']; $ToMonth = $row['ToMonth']; function monthNames($from, $to){ $range=array(); for($i=$from; $i<=$to; $i++){ $range[$i]=date('M', mktime(0,0,0,$i)); } return $range; } $month_ = implode("' ', ",monthNames($FromMonth,$ToMonth)); foreach( monthNames($FromMonth, $ToMonth) as $month){ $sql = "SELECT MonthName, SUM(WorkingDays) AS WorkingDays FROM working_days WHERE MonthName IN ('$month') GROUP BY MonthName"; $res = mysql_query($sql, $con); while($row = mysql_fetch_array($res)){ $WorkingDays = $row['WorkingDays']; } echo $WorkingDays; } ?> the output of this code is: 232423 and when I change this line: $WorkingDays = $row['WorkingDays']; to $WorkingDays += $row['WorkingDays']; the output is: 234770 I correct output should be: 70 Any help is highly appreciated. Thank you very much.. How to do #3 by a PHP page instead? mainly so that there wouldn't be a need to export the sql after doing #2 then import it into the online phpmyadmin(#3) #1. Convert database from foxpro to sql #2. Change some fields in the sql table #3. Upload to phpmyadmin Is it possible to create a code to export from the server and then import the sql online? like by making use of mysql_fetch_array() and insert into In a Switch statement, can you give the Default: a specific name, maybe like this... switch ($resultsCode){ // Missing Primary Key. case 'COMMENT_MISSING_KEYS_2050': echo '<h1>System Error</h1>'; echo '<p>A Fatal Error has occurred. Please contact the System Administrator. (2050)</p>'; break; default 'DEFAULT_CATCHALL_ERROR_CODE_9999': echo '<p>You have reached the catch-all error code... (9999)</p>'; break; Debbie This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=316454.0 The Script:
$desired_width = 110; if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; $tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())"; $tqr = mysqli_query($dbc, $tqs); // Select the ID numbers of the last inserted images and store them inside an array. // Use the implode() function on the array to have a string of the ID numbers separated by commas. // Store the ID numbers in the "image_file_id" column of the "thread" table. $tqs = "SELECT `id` FROM `images` WHERE `image_file` IN ('$new_image_name')"; $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc)); $fetch_array = array(); $row = mysqli_fetch_array($tqr); $fetch_array[] = $row['id']; /* * This prints e.g.: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 ) */ print_r($fetch_array); // Goes over to create the thumbnail images. $src = $target_path; $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/" . $new_image_name; make_thumb($src, $dest, $desired_width); } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } }Hey, sorry that I am posting this darn image upload script again, I have this almost finished and I am not looking to ask more questions when it comes to this script specifically. With the script above I have that part where the script should store the ID numbers (the auto_increment column of the table) of the image files inside of one array and then the "implode()" function would get used on the array and then the ID numbers would get inserted into the "image_file_id" column of the "thread" table. As you can see at the above part the script prints the following: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 )And I am looking to insert into the column of the table the following: 542, 543, 544I thought of re-writing the whole image upload script since this happens inside the for loop, though I thought maybe I could be having this done with the script as it is right now. Any suggestions on how to do this? Hey, I would like to get some practice in the following areas: - arrays (including multidimensional and associative) - functions and their return values I would appreciate it if anyone could give me/point me to some exercises/challenges. Thanks! I am trying to learn PHP basics, and I just cant figure out a way to insert color when certain conditions are met. In my code below, I want to print out red color on lets say, odd numbers from 20-49. Appreciate your help big time! <?php for ($i=20; $i<=49; $i++){ echo "$i<br>"; } ?> Hi, Hope this is the right place for this... I have php routines that print itineraries. For some reason the timestamp (1351378800) returns the same date Sunday 28th October (2012) as the time stamp (1351465200). $count = 0; while ($count <= ($nights+1)) { echo date ('l', $startdate1)." (".$startdate1.")"; echo "<br>"; echo date ('jS F', $startdate1); $startdate1 += 86400; // more code } Any ideas? Many thanks, Peter I wanna give error messages if the user dont enter their name, email or comments. I trıed to do it but mine didnt work. Please help me do it. Index.php page Code: [Select] <html> <head> <title>Guestbook</title> </head> <body> <font color="#CC0000" size="+2">Please sign our guestbook</font> <br \> <br \> <?php echo "<form name=\"Guestbook\" action=\"confirm.php\" method=\"post\">\n"; echo "<table bgcolor=\"#DAE5CD\">\n"; echo " <tr>\n"; echo " <td valign=\"top\">Name: </td>\n"; echo " <td><input type=\"text\" name=\"name\" size=\"25\" value=\"Your Name\"></td>\n"; echo " </tr>\n"; echo " <tr>\n"; echo " <td valign=\"top\">E-mail:</td>\n"; echo " <td><input type=\"text\" name=\"email\" size=\"25\" value=\"example@mail.com\"></td>\n"; echo " </tr>\n"; echo " <tr>\n"; echo " <td valign=\"top\">Comments:</td>\n"; echo " <td><textarea rows=\"5\" cols=\"30\" name=\"comments\">Comments</textarea></td>\n"; echo " </tr>\n"; echo " <tr>\n"; echo " <td></td>\n"; echo " <td align=\"right\"><input type=\"submit\" name=\"submit\" value=\"Submit\"> <input type=\"reset\" value=\"Clear\"> </td>\n"; echo " </tr>\n"; echo "</table>\n"; echo "</form> "; ?> </body> </html> confirm.php page Code: [Select] <html> <head> <title> Submission receieved! </title> </head> <body> <font size="+2" color="#00B0EB">Your submission has been sent successfully!</font><br /> <br /> <?php //extract($_REQUEST); if (!isset($_POST["$submit"])) { if (empty($_POST["name"])) { echo "Please enter your name!"; } else if (empty($_POST["email"])) { echo "Please enter your E-mail"; } else if (empty($_POST["comments"])) { echo "Please enter some text"; } } ?> <table bgcolor="#DAE5CD" width="%50" cellpadding="5"> <tr> <td valign="top" width="75">Name : </td> <td> <?php echo $_POST["name"];?> </td> </tr> <tr> <td valign="top">E-Mail : </td> <td> <?php echo $_POST["email"]; ?> </td> </tr> <tr> <td valign="top">Comments :</td> <td> <?php echo $_POST["comments"]; ?> </td> </tr> </table> </body> </html> Alright, this is the code that i cant seem to get working. Its supposed to update the pin_lock field in my database. I have two databases that it needs to read from, the Account database to verify the login, then the Game database to modify the pin_lock field. It comes up that its sucessfully modified the entry but when i check it, its still the same as it was before. session_start(); if ($_POST["vercode"] != $_SESSION["vercode"] OR $_SESSION["vercode"]=='') { print("<center>Incorrect verification code!"); die(); } require_once('config.php'); mysql_select_db($accdb); $accountid=$_POST['accountid']; $pass=$_POST['pass']; $email=$_POST["email"]; $idnumber=$_POST["question"]; $phone=$_POST["answer"]; session_start(); if(!$_POST["accountid"]) { print("<center>Account ID Field Empty!"); die(); } if(!$_POST["email"]) { print("<center>E-mail Address Field Empty!"); die(); } if(!$_POST["question"]) { print("<center>Security Questions Field Empty!"); die(); } if(!$_POST["answer"]) { print("<center>Answer Field Empty!"); die(); } if(!ereg("^[0-9a-z]{4,12}$",$accountid)) { print("<center>Account ID Only letters from \"a\" to \"z\" and numbers, lenght of 4 to 12 characters"); die(); } if(!ereg("^[0-9a-z]{4,14}$",$pass)) { print("<center>Password Only letters from \"a\" to \"z\" and numbers, lenght of 4 to 14 characters"); die(); } if(!ereg("^[0-9a-zA-Z_]{4,128}$", (strtr($email, Array('@'=>'','.'=>''))))) { print("<center>E-mail Only letters a to z and special chars @ . are allowed!"); die(); } if($_POST["pass"]!=$_POST["pass2"]) { print("<center>Passwords do not match!"); die(); } $ac = mysql_fetch_array(mysql_query(sprintf("SELECT * FROM account WHERE name='$accountid'"))); if (!$ac) { print("<center>Account ID does not exist!"); die(); } $em = mysql_fetch_array(mysql_query(sprintf("SELECT * FROM account WHERE name='$accountid' AND email='$email'"))); if (!$em) { print("<center>E-mail is incorrect!"); die(); } $q = mysql_fetch_array(mysql_query(sprintf("SELECT * FROM account WHERE name='$accountid' AND idnumber='$idnumber'"))); if (!$q) { print("<center>Security Question is incorrect!"); die(); } $an = mysql_fetch_array(mysql_query(sprintf("SELECT * FROM account WHERE name='$accountid' AND phone='$phone'"))); if (!$an) { print("<center>Answer is incorrect!"); die(); } $ac = mysql_fetch_array(mysql_query(sprintf("SELECT * FROM account WHERE name='$accountid'"))); mysql_select_db($gamedb); $temp["query"] = sprintf("UPDATE cq_user SET lock_key='0' WHERE account_id='$selectedid'"); if (!mysql_query($temp["query"])) { die(mysql_error()); } else { print("<center>You bank pin has been removed!"); } Any ideas what is wrong with it? Hi all, I need some help. My ob_get_contents() is empty and gives me a empty file everytime. I tried different cache script it is still the same. I have also tried fwrite($fp, 'hello') In this case, it successfully writes to the file. But when i use ob_start and ob_get_contents, it will be empty. can anyone please advice. My simplified script is here <?php // Settings $cachedir = 'cache/'; // Directory to cache files in (keep outside web root) $cachetime = 600; // Seconds to cache files for $cacheext = 'html'; // Extension to give cached files (usually cache, htm, txt) // Ignore List $ignore_list = array( '/rss.php', '/search/' ); // Script $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page $cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create $ignore_page = false; for ($i = 0; $i < count($ignore_list); $i++) { $ignore_page = (strpos($page, $ignore_list[$i]) !== false) ? true : $ignore_page; } $cachefile_created = ((@file_exists($cachefile)) and ($ignore_page === false)) ? @filemtime($cachefile) : 0; @clearstatcache(); // Show file from cache if still valid if (time() - $cachetime < $cachefile_created) { //ob_start('ob_gzhandler'); @readfile($cachefile); //ob_end_flush(); exit(); } // If we're still here, we need to generate a cache file ob_start(); ?> All My HTML AND PHP CODES TO RUN THE SITE <?php // Now the script has run, generate a new cache file $fp = @fopen($cachefile, 'w'); // save the contents of output buffer to the file @fwrite($fp, ob_get_contents()); @fclose($fp); ob_end_flush(); ?> Hello, I have made a PHP script that will feed an existing XML file. The file stores song details like, title, name of singer etc ... Now the file structure is like this for the moment: Code: [Select] <?xml version="1.0" encoding="UTF-8"?> <music> <song> <title>Without me</title> <artist>Eminem</artist> <url>songs/coreIssues.mp3</url> <image>img/den.jpg</image> <discspeed>11</discspeed> </song></music> But I need it to be: Code: [Select] <?xml version="1.0" encoding="UTF-8"?> <music> <song mainTitle="Eminem - Without me"> <title>Without me</title> <artist>Eminem</artist> <url>songs/coreIssues.mp3</url> <image>img/den.jpg</image> <discspeed>11</discspeed> </song></music> I need it to be like that so if I want to delete a song from the list I just check for the element which will have a unique mainTitle and then delete that element with all it's details. Now, I've searched on Google for some solutions but didn't find any yet. Anyone here knows how to do this? Thanks! |