PHP - Check If Query Exists In An Array.
Hey Guys,
I need some assistance, hopefully there is just a simple command that I am not aware of or an easy answer to this. Suppose I have an array with x amount of values... $arr = array("111111" => 10, "222222" => 20); And i have a query.. mysql_query("SELECT * FROM table WHERE table.zip = "111111" "); Suppose I want to modify the query, so it can check if table.zip exists anywhere in $arr, regardless of length of array. And Select the value that the array location refers to. So I need it to check if "111111" is anywhere in the array, and then take the value 10. The example I am applying this to is that I have a database full of business addresses/zip codes and a database full of every zip code in country. So I have a script to get every zip within x miles, and the distance from it, but need to be able to apply it when I query my business addresses to see if it exists within x miles. Thanks! Greg Similar TutorialsI am trying to compare an array containing required questions to an array holding survey responses. When a user submits a survey, I take the $_POST array and write the values to a new array called $surveyResponseArray. How can I determine if $surveyResponseArray exists?
Edited February 16 by SaranacLake What is the best/proper way to check if a supplied URL goes to an actual image? My site will allow users to enter an image URL (like "http://example.com/images/monkey.jpg"). I will store the URL they enter in a MySQL database and then will call it up later and do some resizing to these images. But I don't want to try to do any resizing if the URL they supply doesn't actually go to an image, or if it's blank (i.e. the user didn't enter a URL yet). So basically, I will run a MySql query to pull back the contents of the column called "imageurl". Let's say those contents are stored in a variable called $imageurl. This is what I'm trying to accomplish.... Code: [Select] if ($theimageurl does NOT contain a URL to an image OR is blank) { // do this } else { //run my resizing code } I guess i could do this to check to see if it's blank, but not sure this is proper/most efficient way to check that part of the issue... Code: [Select] if (trim($theimageurl) == "") But greater than the "is it blank" concern is that people may enter URLs that just to a regular website so whether it's at this point in my code (or for security, I should probably do it BEFORE inserting it into my database :/ ) so curious if there are any functions that check to see if it's an image URL or not. I know of file_exists, but I'm pretty sure that's just checking to see if a file exists and doesn't check image URLs. Any info/suggestions would be appreciated as always! And if there are any recommended functions to check/clean the user-entered URL BEFORE it's entered into the database, please share Thanks! All, In my registration script I am trying to check if an email address already exists (yawn I know), and I am stuck. The code highlighted in bold is where I want to check if the email exists (notice that form checking is done above that, including sorting out the email address that the user enters) and if it doesnt insert data into the table. Trouble is that on loading the page it simply states the 'already submitted' error before an email is even entered into the form: Code: [Select] if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email']) AND ($_POST['password']) && !empty($_POST['password'])){ $name = mysql_escape_string($_POST['name']); // Turn our post into a local variable $email = mysql_escape_string($_POST['email']); $password = mysql_escape_string($_POST['email']);// Turn our post into a local variable } $name = mysql_escape_string($_POST['name']); $email = mysql_escape_string($_POST['email']); $password = mysql_escape_string($_POST['password']); if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){ // Return Error - Invalid Email $msg = 'The email you have entered is invalid, please try again.'; }else{ // Return Success - Valid Email $msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been sent to your email.'; } $hash = md5( rand(0,1000) ); // Generate random 32 character hash and assign it to a local variable. // Example output: f4552671f8909587cf485ea990207f3b [b]$emailCheck = mysql_query("SELECT email FROM users WHERE email = '".$email."'"); if (mysql_num_rows($emailCheck) > 0) { echo "already submitted"; } else {[/b] // We have a match, activate the account mysql_query("INSERT INTO users (username, password, email, hash) VALUES( '". mysql_escape_string($name) ."', '". mysql_escape_string(md5($password)) ."', '". mysql_escape_string($email) ."', '". mysql_escape_string($hash) ."') ") or die(mysql_error()); Thanks in advance, G Hello, I want to check when adding a new user, that if there are 2 records that has the same recruiter id, it's should give an error, if less, than it makes him complete the registration Also check if the National ID number is not assigned to another user, so if there is a record that has it, it should give and error, if it's unavailable, it should let him complete the registration here is my code register.html Code: [Select] <html> <form action="post.php" method="post"> <table> <tr><td>First Name: <input type="text" name="fname" /></td></tr> <tr><td>Middle Name: <input type="text" name="mname" /></td></tr> <tr><td>Last Name: <input type="text" name="lname" /></td></tr> <tr><td>Mobile: <input type="text" name="mobile" /></td></tr> <tr><td>Telephone: <input type="text" name="tel" /></td></tr> <tr><td>Address: <input type="text" name="address" /></td></tr> <tr><td>Job Title: <input type="text" name="job" /></td></tr> <tr><td>Company: <input type="text" name="company" /></td></tr> <tr><td>National ID Number: <input type="text" name="nid" /></td></tr> <tr><td>Recruiter ID: <input type="text" name="recruiteris" /></td></tr> <tr><td>Email: <input type="text" name="email" /></td></tr> <tr><td>Password: <input type="password" name="password" /></td></tr> <tr><td>Type: <input type="text" name="type" /></td></tr> <tr><td><input type="submit" /></td></tr> </table> </form></html> post.php Code: [Select] <?php $sql="INSERT INTO users (id,fname, mname, lname, mobile, tel, address, job, company, nid, recruiteris, email, password, type) VALUES ('','$_POST[fname]','$_POST[mname]','$_POST[lname]','$_POST[mobile]','$_POST[tel]','$_POST[address]','$_POST[job]','$_POST[company]','$_POST[nid]','$_POST[recruiteris]','$_POST[email]','$_POST[password]','$_POST[type]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; echo "<br />"; echo "<a href='http://waw-eg.com/admin/register.html'>Add More Client? Click Here</a><br/>"; echo "<a href='http://waw-eg.com/admin/Users.php'>View Users Click Here</a>"; mysql_close($con) ?> hi, how can i check if a username exists? i tried this
$usrsql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $usrres = mysql_query($usrsql); $usrcount = mysql_num_rows($usrres); if($usrres && mysql_num_rows($usrcount)>0) { die("Username is already taken!"); } I'm working with a registration/login system from a tutorial. It's got email validation to make sure it does not exist but I'm struggling to add the same to the username field: Working code: Code: [Select] <?php include ('database_connection.php'); if (isset($_POST['formsubmitted'])) { $error = array();//Declare An Array to store any error message if (empty($_POST['name'])) {//if no name has been supplied $error[] = 'Please Enter a name ';//add to array "error" } else { $name = $_POST['name'];//else assign it a variable } if (empty($_POST['e-mail'])) { $error[] = 'Please Enter your Email '; } else { if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) { //regular expression for email validation $Email = $_POST['e-mail']; } else { $error[] = 'Your EMail Address is invalid '; } } if (empty($_POST['Password'])) { $error[] = 'Please Enter Your Password '; } else { $Password = $_POST['Password']; } if (empty($error)) //send to Database if there's no error ' { // If everything's OK... // Make sure the email address is available: $query_verify_email = "SELECT * FROM members WHERE Email ='$Email'"; $result_verify_email = mysqli_query($dbc, $query_verify_email); if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false) echo ' Database Error Occured '; } if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email . // Create a unique activation code: $activation = md5(uniqid(rand(), true)); $query_insert_user = "INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$name', '$Email', '$Password', '$activation')"; $result_insert_user = mysqli_query($dbc, $query_insert_user); if (!$result_insert_user) { echo 'Query Failed '; } if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull. // Send the email: $message = " To activate your account, please click on this link:\n\n"; $message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation"; mail($Email, 'Registration Confirmation', $message, 'From: Admin@TheGameCo.Com'); // Flush the buffered output. // Finish the page: echo '<div class="success">Thank you for registering! A confirmation email has been sent to '.$Email.' Please click on the Activation Link to Activate your account </div>'; } else { // If it did not run OK. echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>'; } } else { // The email address is not available. echo '<div class="errormsgbox" >That email address has already been registered. </div>'; } } else {//If the "error" array contains error msg , display them echo '<div class="errormsgbox"> <ol>'; foreach ($error as $key => $values) { echo ' <li>'.$values.'</li>'; } echo '</ol></div>'; } mysqli_close($dbc);//Close the DB Connection } // End of the main Submit conditional. ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Game Name - Home</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div id="container"> <div id="header"> <?php include("includes/header.php"); ?> </div> <div id="nav"> <?php include("includes/nav.php"); ?> </div> <div id="content"> <form action="index.php" method="post" class="registration_form"> <fieldset> <legend>Registration Form</legend> <p>Create A new Account<br />Already a member? <a href="login.php">Log in</a></p> <div class="elements"> <label for="name">Username:</label> <input type="text" id="name" name="name" size="25" /> </div> <div class="elements"> <label for="e-mail">E-mail:</label> <input type="text" id="e-mail" name="e-mail" size="25" /> </div> <div class="elements"> <label for="Password">Password:</label> <input type="password" id="Password" name="Password" size="25" /> </div> <div class="submit"> <input type="hidden" name="formsubmitted" value="TRUE" /> <input type="submit" value="Register" /> </div> </fieldset> </form> </div> <div id="footer"> <?php include("includes/footer.php"); ?> </div> </div> </body> </html> I've tried adding this after the email verification: Code: [Select] // Make sure the user is available: $query_verify_user = "SELECT * FROM members WHERE Username ='$name'"; $result_verify_user = mysqli_query($dbc, $query_verify_user); if (!$result_verify_user) { echo ' Database Error Occured '; } } if (mysqli_num_rows($result_verify_user) == 0) { // IF no previous user is using this user . But that just returns me with: It works to stop username/email duplication but now returns: Query Failed You could not be registered due to a system error. We apologize for any inconvenience. Not sure where I'm going wrong tbh. What is the best/proper way to run an image URL from an external site through a check to see if the image actually exists? I am trying to use file_exists() but it's not recognizing image URLs from external sites as existing, so there must be some other way to deal with external URLs. In other words, the image does exist but file_exists() says it doesn't. Can anyone help? Hello , Im trying to make a very simple link trade script , which checks in a page exists and after searches to that page to find a link (in this case my link). But i got stuck in the lalst step of finding my link on a given page. Hope you can help me with that Code: [Select] <?php require_once('Connections/my_conn.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $myurl= 'http://mywebsite.com'; //check if the remote site url exists function url_exists($url) { $ch = @curl_init($url); @curl_setopt($ch, CURLOPT_HEADER, TRUE); @curl_setopt($ch, CURLOPT_NOBODY, TRUE); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $status = array(); preg_match('/HTTP\/.* ([0-9]+) .*/', @curl_exec($ch) , $status); } //check if my link exists in the remote site if(($status[1] == 200) && ($myurl== )); { //Insert into database code here } ?> I would like a little help on how to check if my link exist in the trader's url. Thanks in advance Hello. I want to check if an e-mail address is stored into a database. I've found this type of code: Code: [Select] function verifmail($email) { db_connect(); if (mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$email';"))) { return 1; } else { return 0; } } Is it correct ? Is there any other way? Hi, I am creating a temporary table. I need to check if the table already exists or not. If exists, I have to use the existing data else have to create a new temporary table. I can use 'Create If Not Exists'. How practical is this query? any issues with the performance? If the table exists it will be a huge data, I don't want to loose that data because recreating is an un-necessary load on the database. Hi, I just want to know how to check if a row/record already exists for a given table, but this code gives me message in browser: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in myTest.php This is the the snippet I am running: Code: [Select] <?php $connxn=mysql_connect("localhost","root"); $db=mysql_select_db("siliconvalley"); $toyNodePath="#document/siliconValleyHELLO"; $queryA=mysql_query("SElECT FROM pathexpress (path_express) WHERE path_express='$toyNodePath'");//make sure AT MOST ONE ROW EXISTS!! if(mysql_num_rows($queryA)==1) print "ALREADY IN table pathexpress!"; else { mysql_query("INSERT INTO pathexpress (path_express) VALUES ('$toyNodePath')"); print "ADDED $toyNodePath to table pathexpress!"; } ?> Please, any help is greatly appreciated! Hey guys im automatically generating a folder location to place some image files the user has uploaded into. If this folder doesnt exist how can i make it? $target_path_thumbnails = "http://www.worldwidelighthouses.com/Images/".$folderlocation."/".$foldername."/Mini/"; Thats the path style. Danny Pehaps this is kidstuff but i'm a kid at heart. I have only 1 form field on a form User enters a special code in the form. Once submitted the form is queried against a mysql database to see if the code exists. If code does not exist it must be reentered. If code exists then redirected. basically its like "get to the next page if you have the code" thanks Hey, so I'm trying to check the database if the user and email already exists when registering. <?php include_once('includes/config.php'); if(isset($_POST['submit'])) { $username = $_POST['username'] ? trim($_POST['username']) : null; $password = md5($_POST['password']) ? trim($_POST['password']) : null;; $email = ($_POST['email']); $message = ""; if(empty($username) || empty($password) || empty($email)) { $message = "All fields required"; } else { $sql = "SELECT COUNT(username) AS userNum FROM users WHERE username = :username"; $sql = "SELECT COUNT(email) AS emailNum FROM users WHERE email = :email"; $stmt = $db->prepare($sql); $stmt->bindValue(':username', $username); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if($row['userNum'] >0) { die("That username already exists!"); } elseif($row['emailNum'] > 0) { die("That email already exists!"); } $sql = "INSERT INTO users (username, password, email) VALUES (:username, :password, :email)"; $stmt = $db->prepare($sql); $stmt->bindValue(':username', $username); $stmt->bindValue(':password', $password); $stmt->bindValue(':email', $email); $result = $stmt->execute(); if($result) { $message = "Registration was successful"; } } } ?> If I remove this line " $sql = "SELECT COUNT(email) AS emailNum FROM users WHERE email = :email"; the code works but only checks the username. How can I check both? Please help before this script drives me insane. It tries to download a skin from Minecraft. It works fine, except, if it returns an error code, (301, 302, 404), don't download, and using my image (char.png) as a replacement. I can get the error code, except, no matter how I compare it, it will a) still say it's 302 or b) not work at all. Here's my code: userskin.inc.php > <?php require('class.mineuser.php'); if(!isset($_GET['width']) || strlen(trim($_GET['width'])) == 0 || !isset($_GET['height']) || strlen(trim($_GET['height'])) == 0) { $x = 16; $y = 16; } else { $x = $_GET['width']; $y = $_GET['height']; } if(isset($_GET['refresh'])) $refresh = true; else $refresh = false; if(isset($_GET['debug'])) $debug = true; else $debug = false; $http = curl_init("http://www.minecraft.net/skin/{$_GET['user']}.png"); curl_setopt($http, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($http); $http_status = curl_getinfo($http, CURLINFO_HTTP_CODE); $resp = preg_match("/302/", $http_status, $match); $code = $match[0]; if($code == 302) { mineuser::downloadSkin($_GET['user'], $_GET['path'], $code, $refresh); mineuser::getFace($_GET['user'].".png", $x, $y, $_GET['path'], $code, $debug); } else { mineuser::getFace("char.png", $x, $y, $_GET['path'], $code, $debug); } class.mineuser.php > <?php class mineuser { public static function downloadSkin($user, $path = "", $resp, $new = false) { if($resp !== 302) { //Checks if $new is true, if it is, then delete $user.png and download a new one. if($new == true) unlink("$path/$user.png"); //Checks if the users skin already exists (faster loading time) if(!file_exists("$path/$user.png")) { $fh = fopen("$path/$user.png", "w"); $file = file("http://www.minecraft.net/skin/$user.png"); foreach($file as $char) //Since it's an array, we use a foreach loop and write each character individually fwrite($fh, $char); fclose($fh); //Close our file handler. } } else { } } //End of function downloadSkin() public static function getFace($user, $width, $height, $path, $resp, $debug = true) { $im = imagecreatetruecolor($width, $height); if($debug == false) { header("Content-type: image/png"); } if($resp === 302) { $image = imagecreatefrompng("$path/char.png"); } else { $image = imagecreatefrompng("$path/$user"); } imagecopyresampled($im, $image, 0, 0, 8, 8, $width, $height, 8, 8); imagepng($im); imagedestroy($im); } //End of function getFace() } ?> please help before i go insane Thanks in advance I am adding new entries into a MySQL table via a php script. The script works fine, but I want to prevent duplicate entries. How can I check if an entry already exists on the table before initiating the query to write to the table. It is for a user registration type of system. The php script rights "AccountName" and "PassWord" to the table called "Accounts". This was my attempt to check if it exists: $query = "INSERT INTO Accounts(AccountName, Password)VALUES ('".$Accn."','".$Pwwd."')"; $Check = mysql_query("SELECT * FROM Accounts"); while($row = mysql_fetch_array($Check)) { $Account = $row['AccountName']; } if($accn != Account) { mysql_query($query); } Where $accn = the new accountname entered. I am trying to compare the new AccountName(accn) that was entered with the array of all AccountNames already in the database, and if does not already exists, then add it. Hello all, I am working on an upload script for a client. The script generates a random 32 bit string (to use as an ID). I want it to check if that folder exists and, if not, create it and put the files in it. Here is the script I have so far: <?php /******************************************* /* contact_us_process.php /* Author: Brandon Pence (brandonpence@gmail.com) /* /* Desc: This page process and checks the submitted form. /* /* variable meaning /* -------- ------- /* $FieldCheck Instance of the FieldCheck class. /* /******************************************/ session_start(); require ("./inc/include.inc.php"); //include Field Check Class include("classes/FieldCheck.php"); $FieldCheck = new FieldCheck; if(file_exists("uploads/$id")){ echo 'Folder Exists!'; }else{ echo 'Folder does not exist. Create folder.'; } //mkdir("uploads/$id",0777,true); $target_path = "uploads/$id/"; $i = 0; while($i < 3){ $target_path = $target_path . basename( $_FILES['uploadedfile']['name'][$i]); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'][$i], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name'][$i]). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } $i++; } if (!$FieldCheck->checkName($your_name)){ $errors['your_name'] = "Your name is not valid.";} if (!$FieldCheck->isEmpty($your_date)){ $errors['your_date'] = "Your date is not valid.";} if (!$FieldCheck->isEmpty($your_message)){ $errors['your_message'] = "Your message is not valid.";} foreach($_POST as $key=>$value){ $fields[$key] = $value; } //print_r($_POST); //check for error messages if (isset($errors)) { $_SESSION['errors'] = $errors; $_SESSION['fields'] = $fields; $_SESSION['error_msg'] = "Errors found! Please review your entries."; $url = "./testimonials.php?action=errors"; header ("Location: $url"); exit; }else{ // multiple recipients $to = 'email@email.com'; // note the comma // subject $subject = '[Domain Name.com] Testimonials Form Submission'; // message $message = ' Name: '.$your_name.' Date: '.$your_date.' Message: '.$your_message.' '; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= 'To: Example <email@example.com>' . "\r\n"; $headers .= 'From: Example <email@example.com.com>' . "\r\n"; $headers .= 'X-MAILER: PHP'.phpversion(); $headers .= 'Reply-To:email@example.com'; // Mail it $mail = mail($to, $subject, $message); //mail("$to", "$subject", "this is a test message, if you are reading this the email was sent successfully."); //savvy $_SESSION['error_msg'] = "Your email has been sent. Thank you for contacting us."; header( "Location: testimonials.php?action=success" ); } ?> It always outputs folder exists, even though it doesn't. My form is this: function random_string($p_length) { $char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $char_list .= "abcdefghijklmnopqrstuvwxyz"; $char_list .= "1234567890"; $random = ""; srand((double) microtime() * 1000000); for($i = 0; $i < $p_length; $i++) { $random .= substr($char_list, (rand() % (strlen($char_list))), 1); } return $random; } <form method="POST" action="contact_us_process.php" class="cmxform" enctype="multipart/form-data"> <?php if ($_GET['action'] == 'success' && isset($_SESSION['error_msg'])){ echo '<div class="success">'.$_SESSION['error_msg'].'</div>'; unset($_SESSION['error_msg']); }else{ if(isset($_SESSION['error_msg'])){ echo '<div class="error">'.$_SESSION['error_msg'].'</div>'; unset($_SESSION['error_msg']); } } ?> <fieldset style="margin:20px;width:350px;height:450px;background-color:none;"> <legend>Contact Us</legend> <ol> <li> <label for="your_name">Your Name</label> <input type="text" name="your_name" size="50" class="textbox" <?php if (isset($errors['your_name'])){echo 'class="input_red"';}?> <?php if (isset($fields['your_name'])){echo 'value="'.$fields['your_name'].'"';}?>/> <?php if (isset($errors['your_name'])){ echo '<span class="error_box"> '.$errors['your_name'].'<span class="error-pointer"> </span></span>';}else{?> <span class="hint">Tell us your name! It's nice to meet you!<span class="hint-pointer"> </span></span> <?php } ?> </li> <div class="clear"></div> <li> <label for="your_date">Your Date</label> <input type="text" name="your_date" size="50" class="textbox" <?php if (isset($errors['your_date'])){echo 'class="input_red"';}?> <?php if (isset($fields['your_date'])){echo 'value="'.$fields['your_date'].'"';}?>/> <?php if (isset($errors['your_date'])){ echo '<span class="error_box"> '.$errors['your_date'].'<span class="error-pointer"> </span></span>';}else{?> <span class="hint">Let's keep in touch!<span class="hint-pointer"> </span></span> <?php } ?> </li> <div class="clear"></div> <li> <label for="your_message">Your Message</label> <textarea rows="3" cols="40" name="your_message" class="textarea"<?php if (isset($errors['your_message'])){echo 'class="input_red"';}?>><?php if (isset($fields['your_message'])){echo $fields['your_message'].'</textarea>';}else{echo '</textarea>';}?> <?php if (isset($errors['your_message'])){ echo '<span class="error_box"> '.$errors['your_message'].'<span class="error-pointer"> </span></span>';}else{?> <span class="hint">What's on your mind?<span class="hint-pointer"> </span></span> <?php } ?> </li> <li> <input name="uploadedfile[]" type="file" /> </li> <li> <input name="uploadedfile[]" type="file" /> </li> <li> <input name="uploadedfile[]" type="file" /> </li> <?php $random_string = random_string(32); //This will return a random 10 character string?> <input type="hidden" value="<?php echo $random_string;?>" name="id"/> <input type="hidden" name="MAX_FILE_SIZE" value="10000000" /> <div class="submit_box"> <input type="submit" value="Get in touch with us!" name="submit" class="submit"> </div> </ol> </fieldset> </form> Can anyone help me with the "if it exists, move on, if it doesnt, create folder" part? Hello all, I have another project I’m working on a php login and I am inserting a record in the db I’m checking the table to see if it exists or not so there can’t be 2 users with the same username but I am working with create the form submits but nothing is inserted. Also appreciate suggestions in code to make my php better. <?php //mySQL database config require_once "config.php"; // Define all variables and initialize them as 'empty' $name = $username = $password = $password2 = ""; $nameerror = $usernameerror = $passworderror = $password2error = ""; // Process data when the form is submitted. if($_SERVER["REQUEST_METHOD"] == "POST") { //Name check if(empty(trim($_POST["name"]))) { $nameerror = "Please enter a name."; } else { $name = trim($_POST["name"]); } // Validate 'Username' if(empty(trim($_POST["username"]))) { $usernameerror = "Please enter a Username."; } else { // Prepare a SELECT statement. $sql = "SELECT userid FROM users WHERE username = :username"; if($stmt = $pdoConn->prepare($sql)) { // Bind variables to prepared statement as parameters $stmt->bindParam(":username", $param_username, PDO::PARAM_STR); // Set parameters $param_username = trim($_POST["username"]); // Attempt to execute prepared statement if($stmt->execute()) { if($stmt->rowCount() == 1) { $usernameerror = "Username is already taken."; } else { $username = trim($_POST["username"]); } } else { echo "Something went wrong with SELECT, please try again later."; } } // Close $stmt unset($stmt); } // Validate Password if(empty(trim($_POST["password"]))) { $passworderror = "Please enter a password."; } else if (strlen(trim($_POST["password"])) < 6) { $passworderror = "Password must have at least 6 characters."; } else { $password = trim($_POST["password"]); } // Validate Confirm Password. if(empty(trim($_POST["password2"]))) { $password2error = "Please confirm your password"; } else { $pass2 = trim($_POST["password2"]); if(empty($password2error) && ($password != $pass2)) { $password2error = "Passwords <b>DID NOT</b> match."; } } //Check for inputs on form to continue. // Error checks or input checks. if(empty($name) && empty($username) && empty($password) && empty($password2)) { // Prepare SELECT statement $sql = "INSERT INTO users (name, username, password) " . "VALUES (:name, :username, :password)"; if($stmt = $pdoConn->prepare($sql)) { // Bind variables to prepared statement as parameters $stmt->bindParam(":name", $param_name, PDO::PARAM_STR); $stmt->bindParam(":username", $param_username, PDO::PARAM_STR); $stmt->bindParam(":password", $param_pass, PDO::PARAM_STR); // Set parameters $para_name = $name; $param_username = $username; $param_pass = password_hash($password, PASSWORD_DEFAULT); // attempt to execute the prepared Statement if($stmt->execute()){ header("Location: ../index.php"); } else { echo "Something went wrong with INSERT"; } } // Close Statement unset($stmt); } // Close connection unset($pdoConn); } ?>
Say you have three tables like this...
STUDENTS (studentid, name)
CLASSES (studentid, classname)
GRADES (studentid, grade)
And not all students have grades yet. If you're doing a mysql query like below, is there anything you can add to the statement to check if a grade exists for each student? So that if while lopping through the results of the main query, I can easily do something with the students who don't yet have a grade yet (like maybe mark their names in red).
I can do this by putting a whole separate mysql query inside the looping of the main query, but that seems terribly inefficient to call the database again for EVERY student.
$sql = "SELECT * FROM students, classes, grades WHERE students.studentid = classes.studentid ORDER BY students.lastname"; $info= mysqli_query($connection, $sql); if (!$info) { die("Database query failed: " . mysqli_error()); } else { //code }Thanks! Greg I need to check (from a Debian server to a Mac CLIENT (not server) machine) to see if a file exists on the file system...not an http server. Here's what I've tried (based on reading at http://www.php.net/manual/en/function.ssh2-exec.php) Code: [Select] <?php function check_remote_files($username, $hostname, $remote_file) { $connection = ssh2_connect($hostname, 22, array('hostkey'=>'ssh-rsa')); if (ssh2_auth_pubkey_file($connection, $username, '/root/.ssh/id_rsa.pub', '/root/.ssh/id_rsa', '')) { echo "Public Key Authentication On Server #2 Successful\n"; } $url = "if ssh $hostname stat $remote_file \> /dev/null 2\>\&1"; $stream=ssh2_exec($connection,$url); stream_set_blocking( $stream, true ); $cmd=fread($stream,4096); fclose($stream); $stream=ssh2_exec($connection,"then"); stream_set_blocking( $stream, true ); $cmd=fread($stream,4096); fclose($stream); $stream=ssh2_exec($connection,"echo File exists"); stream_set_blocking( $stream, true ); $cmd=fread($stream,4096); fclose($stream); $stream=ssh2_exec($connection,"else"); stream_set_blocking( $stream, true ); $cmd=fread($stream,4096); fclose($stream); $stream=ssh2_exec($connection,"echo Not found"); stream_set_blocking( $stream, true ); $cmd=fread($stream,4096); fclose($stream); $stream=ssh2_exec($connection,"fi"); stream_set_blocking( $stream, true ); $cmd=fread($stream,4096); fclose($stream); } ?> NOTHING happens after the echo of Public Key Authentication On Server #2 Successful. I'm running this script from a bash shell. Any ideas what might be wrong? Thanks. |