PHP - Issue Running Query
Its the
Code: [Select] $query = "INSERT INTO hitlist hit_id = ($addIDs_str), player_id = '$playerID'"; Thats the issue, my codes below i cannot figure out how to insert the results, any help would be appreciated Thanks Code: [Select] if (isset($_POST["submit"]) && $_POST["submit"] == "Recall Selected Informants") { //Force POST values to be INTs $addIDs_ary = array_map('intval', $_POST['chkInv']); //Remove any 'false' value $addIDs_ary = array_filter($addIDs_ary); //Check that there was at least one valid value if(count($addIDs_ary)) { //Create comma separated string of the IDs $addIDs_str = implode(',', $addIDs_ary); //Create and run one query to perform all the adds (of the user) $query = "INSERT INTO hitlist hit_id = ($addIDs_str), player_id = '$playerID'"; $sql = "UPDATE players SET Informants = Informants - 1 WHERE id = '$playerID'"; mysql_query($sql) or die(mysql_error()); if(mysql_query($query)) { $selectedCount = count($addIDs_ary); $adddCount = mysql_affected_rows(); echo "{$adddCount} of {$selectedCount} Investigated player(s) were successfully Removed."; if($adddCount != $selectedCount) { echo " You do not have rights to the others."; } }else{ echo "There was a problem running the query.<br>" . mysql_error(); } }else{ echo "Invalid ID data passed."; } } Similar TutorialsHey Guys, I have a DB with two tables, one is field names, the other is the data. So for example, I log in and I am user ID 1..... I need to query the DB to show all fields where user_id = 1 Field1 - Data1 Field2 - Data2 etc etc... This is what I have so far, but I dont get any output... $sql = "SELECT * FROM ".WPSC_TABLE_DATA." WHERE `user_id` == .$cu. ORDER BY id DESC"; $user= $wpdb->get_row($sql); while($user) { echo $user->name .' : '. $user->value .'<br />'; } Can you help please? Hi, I have written some code however when I echo the query it runs it twice... Quote SELECT `description`, `fulldescription` FROM `productdbase` WHERE `keywords` LIKE '%table%'something found.SELECT `description`, `fulldescription` FROM `productdbase` WHERE `keywords` LIKE '%table%'something found. I only have the query once in my code. Any suggesions? Code: [Select] <?php if (isset($_POST['keywords'])){ $keywords = mysql_real_escape_string (htmlentities(trim($_POST['keywords']))); } $errors = array(); if (empty($keywords)) { $errors[] = 'Please enter a search term'; } else if (strlen($keywords)<3) { $errors[] = 'Your search must be three or more characters'; } else if (search_results($keywords) === false) { $errors[] = 'Your search for '.$keywords.' returned no results'; } if (empty($errors)) { search_results ($keywords); } else{ foreach($errors as $error) { echo $error, '</br>'; } } ?> <?php function search_results ($keywords) { $returned_results = array(); $where = ""; $keywords = preg_split('/[\s]+/', $keywords); $total_keywords = count($keywords); foreach($keywords as $key=>$keyword) { $where .= "`keywords` LIKE '%$keyword%'"; if ($key != ($total_keywords - 1)) { $where .= " AND "; } } $query_string = "SELECT `description`, `fulldescription` FROM `productdbase` WHERE $where"; echo $query_string; $query = mysql_query($query_string); if ($results_num === 0) { return false; }else{ echo 'something found.'; } } ?> Hi i was wondering what im doing wrong, im trying to insert a query for submit button, it works if i run it straight in mysql, but not working when linked through php. Im just doing it for testing purpose right now only, so when i see that it works i will use another query. here it is Code: [Select] <?php include('config.php'); if($_SESSION['username']){ if(isset($_POST['ASubmit'])){ $query3=("update country set Status='test1' where Uname='Mclovin'");} echo '<td><form name="test" method="post" form id="form1"><label for="test">Status</label> <select name="Status"> <option value="">-----</option> <option value="In process" '.(($row['Status']=='In process')?'selected="selected"':'').'>In process</option> <option value="Approved" '.(($row['Status']=='Approved')?'selected="selected"':'').'>Approved</option> <option value="Denied" '.(($row['Status']=='Denied')?'selected="selected"':'').'>Denied</option> </select><input name="ASubmit" type="submit" value="Update">'; echo $row{'Status'}.'</td></form>'; } ?> I have a php script that I've been running that seems to have been working but now I'm wondering if some of my logic is potentially off. I select records from a db table within a date range which I put into an array called ```$validCount``` If that array is not empty, that means I have valid records to update with my values, and if it's empty I just insert. The trick with the insert is that if the ```STORES``` is less than the ```Quantity``` then it only inserts as many as the ```STORES``` otherwise it inserts as many as ```Quantity```. So if a record being inserted with had Stores: 14 Quantity:12
Then it would only insert 12 records but if it had It would only insert 1 record. In short, for each customer I should only ever have as many valid records (within a valid date range) as they have stores. If they have 20 stores, I can have 1 or 2 records but should never have 30. It seems like updating works fine but I'm not sure if it's updating the proper records, though it seems like in some instances it's just inserting too many and not accounting for past updated records. This is the logic I have been working with:
if(!empty($validCount)){ for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $out[] = $failedUpdate; } } }else{ if($row2["QUANTITY"] >= $row2["STORES"]){ for($i=0; $i<$row2["STORES"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertStore; } } }elseif($row2["QUANTITY"] < $row2["STORES"]){ for($i=0; $i<$row2["QUANTITY"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertQuantity; } } } }
Let's say customer 123 bought 4 of product A and they have 10 locations
customerNumber | product | category | startDate | expireDate | stores Because they purchased less than their store count, I insert 4 records. Now if my ```$validCheck``` query selects all 4 of those records (since they fall in a valid date range) and my loop sees that the array isn't empty, it knows it needs to update those or insert. Let's say they bought 15 this time. Then I would need to insert 6 records, and then update the expiration date of the other 9 records.
customerNumber | product | category | startDate | expireDate | stores There can only ever be a maximum of 10 (store count) records for that customer and product within the valid date range. As soon as the row count for that customer/product reaches the equivalent of stores, it needs to now go through and update equal to the quantity so now I'm running this but it's not running and no errors, but it just returns back to the command line $total = $row2['QUANTITY'] + $validCheck; if ($total < $row2['STORES']) { $insert_count = $row2['QUANTITY']; $update_count = 0; } else { $insert_count = $row2['STORES'] - $validCheck; // insert enough to fill all stores $update_count = ($total - $insert_count); // update remainder } for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $failedUpdate = "UPDATE_FAILED"; print_r($failedUpdate); $out[] = $failedUpdate; } } for($i=0; $i<$insert_count; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $failedInsertStore = "INSERT_STORE_FAILED!!!: " . $ex->getMessage(); print_r($failedInsertStore); $out[] = $failedInsertStore; } }```
Hi All, I have a form that enables the user to know events that occur in a specific city. Most of the time they get the results in a few seconds, despite the fact that many rows in various tables might be searched for detailed infos about the events in that city. However, this form partly relies on a table against which a MySQL event regularly does some operations. If the user uses the form while the event is being executed, they have to wait up to 30 seconds before getting the results, and sometimes only part of the html page is generated. Is there a way to avoid this lengthy waiting time ? I am wondering whether or not the best would be putting the site on maintenance while the event is being executed, with a "please come back in a few minutes" message. Thanks in advance for your help. Hello!
I have a php page which shows a list of customers displayed in an html table format, The first column in the table contains a link for the user to select the row which then navigates to another php page, which is the customer order page. On this page, I want to get certain information based on the name of the customer to prepopulate the customer fields on this form, so I have some php code near the top of the page, as per attached document.
I have checked to ensure that the $_GET['business_name'] contains a value. The query runs fine in myssql and returns only one record when I provide a value for the business_name, however when I run the code in php, the $result variable shows 'Resource id ='7' type='mySQL result'.
I am a total newbie on PHP/MySQL and inherited this application. I have tried to find solutions on line through various forums, but no luck. Perhaps I am not asking/looking for the right question.
Anyway, any assistance would be greatly appreciated.
Attached Files
customer_order_php.php 648bytes
1 downloads Hi everyone... My script register01.php isnt working as expected, it should take variables from register00.php and insert them into the db. It is currently re-loading itself and not inserting, could you take a look at this for me: register00.php Code: [Select] <form enctype="multipart/form-data" method="post" action="register01.php"> <table width="316" height="120" border="0"> <tr><td colspan=2><h1>Register/Sign Up</h1></td></tr> <tr><td>Company Name:</td><td> <input name="company_name" type="text" id="company_name"> </td></tr> <tr><td>Contact Name:</td><td> <input name="contact_name" type="text" id="contact_name"> </td></tr> <tr><td>Contact Number:</td><td> <input name="phone" type="number" id="phone" value="incl. area code"> </td></tr> <tr><td>Address line 1:</td><td> <input name="street1" type="text" id="street1"> </td></tr> <tr><td>Address line 2:</td><td> <input name="street2" type="text" id="street1"> </td></tr> <tr><td>Area:</td><td> <input name="location" type="text" id="location"> </td></tr> <tr><td>City:</td><td> <input name="city" type="text" id="city"> </td></tr> <tr><td>Postcode:</td><td> <input name="postcode" type="text" id="postcode"> </td></tr> <tr><td>Username:</td><td> <input name="username" type="text" id="username"> </td></tr> <tr><td>Password:</td><td> <input name="password" type="password" class="style7" id="password"> </td></tr> <tr><td>Email:</td><td> <input name="email" type="text" class="style7" id="email"> </td></tr> <tr><td>Company Logo:</td><td> <input name="upload" type="file" class="style7" id="upload"> </td></tr> <tr><td>Company Description:</td><td> <textarea rows="20" cols="50" name="premiumuser_description" id="premiumuser_description"></textarea> </td></tr> <tr><td> <input name="Submit" type="submit" value="Register" /> </td></tr> </table> register01.php Code: [Select] <?PHP session_start(); include('db.php'); /* set some validation variables */ $error_message = ""; /* DEFINE THE FUNCTION */ /* ============================================== */ /* ============================================== */ /* DO NOT MODIFY THIS FUNCTION */ function Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path) { $s_path = trim($s_path); $o_path = trim($o_path); $save = $s_path . $save; $file = $o_path . $file; $ext = strtolower(end(explode('.',$save))); list($width, $height) = getimagesize($file) ; if(($width>$t_w) OR ($height>$t_h)) { $r1 = $t_w/$width; $r2 = $t_h/$height; if($r1<$r2) { $size = $t_w/$width; }else{ $size = $t_h/$height; } }else{ $size=1; } $modwidth = $width * $size; $modheight = $height * $size; $tn = imagecreatetruecolor($modwidth, $modheight) ; switch ($ext) { case 'jpg': case 'jpeg': $image = imagecreatefromjpeg($file) ; break; case 'gif': $image = imagecreatefromgif($file) ; break; case 'png': $image = imagecreatefrompng($file) ; break; } imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; imagejpeg($tn, $save, 100) ; return; } /* END OF RESIZE FUNCTION */ //This is the directory where images will be saved $target = "/home/users/web/b109/ipg.removalspacecom/images/COMPANIES/"; $target = $target . basename( $_FILES['upload']['name']); // Connects to your Database session_start(); include ('db.php'); //This gets all the other information from the form /* ============================================== */ /* ============================================== */ /* YOU NEED TO DO SOME VALIDATION AND SANITIZING OF YOUR FORM DATA */ if((!isset($_POST['company_name'])) || (strlen(trim($_POST['company_name'])) <5) || (trim($_POST['company_name']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['company_name'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid company name<br>"; $error_message = $error_message . "Valid names are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['company_name'] . "</font><hr>"; } /* END validating company_name */ /* =============================================== */ if((!isset($_POST['contact_name'])) || (strlen(trim($_POST['contact_name'])) <5) || (trim($_POST['contact_name']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['contact_name'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid contact name<br>"; $error_message = $error_message . "Valid names are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['contact_name'] . "</font><hr>"; } /* END validating contact_name */ /* =============================================== */ if((!isset($_POST['phone'])) || (strlen(trim($_POST['phone'])) <5) || (trim($_POST['phone']) != preg_replace("/[^0-9\s\-\_]/", "", trim($_POST['phone'])))) { /* if it is NOT set, then set the error variable and start building the error message */ $error_message = $error_message . "You must enter a valid phone<br>"; $error_message = $error_message . "Valid phones are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid phone was: <font color="red">' . $_POST['phone'] . "</font><hr>"; }else{ $phone = trim($_POST['phone']); } /* END validating phone */ /* =============================================== */ /* =============================================== */ /* validating the email */ /* create a function */ function validateEmailAddress($email) { return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email); } if(!isset($_POST['email']) || validateEmailAddress($_POST['email']) !=1) { $error_message = $error_message . "You must enter a valid email address<br>"; $error_message = $error_message . 'The invalid email was: <font color="red">' . $_POST['email'] . "</font><hr>"; } /* END validating email */ /* =============================================== */ if((!isset($_POST['street1'])) || (strlen(trim($_POST['street1'])) <5) || (trim($_POST['street1']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['street1'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid address<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['street1'] . "</font><hr>"; } /* END validating street1 */ /* =============================================== */ if((!isset($_POST['street2'])) || (strlen(trim($_POST['street2'])) <5) || (trim($_POST['street2']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['street2'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid address<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['street2'] . "</font><hr>"; } /* END validating street2 */ /* =============================================== */ if((!isset($_POST['premiumuser_description'])) || (strlen(trim($_POST['premiumuser_description'])) <5) || (trim($_POST['premiumuser_description']) != preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/", "", trim($_POST['premiumuser_description'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid address<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['premiumuser_description'] . "</font><hr>"; } /* END validating premiumuser_description */ /* =============================================== * /* =============================================== */ /* this section of code will set up an error message for the username if ANY of the conditions occur 1) checks to see if $_POST['username'] is NOT set 2) if length of username is less than 5 3) if username has anything other than letter, numbers or underscores */ if((!isset($_POST['username'])) || (strlen(trim($_POST['username'])) <5) || (trim($_POST['username']) != preg_replace("/[^a-zA-Z0-9\_]/", "", trim($_POST['username'])))) { /* if username is bad start building the error message */ $error_message = "You must enter a valid username<br>"; $error_message = $error_message . "Valid names are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid name was: <font color="red">' . $_POST['username'] . "</font><hr>"; } /* END validating username */ /* =============================================== */ /* =============================================== */ /* this section of code will set up an error message for the password if ANY of the conditions occur 1) checks to see if $_POST['upassword'] is NOT set 2) if length of upassword is less than 5 3) if upassword has anything other than letter, numbers or underscores */ if((!isset($_POST['password'])) || (strlen(trim($_POST['password'])) <5) || (trim($_POST['password']) != preg_replace("/[^a-zA-Z0-9\_]/", "", trim($_POST['password'])))) { /* if it is NOT set, then set the error variable and start building the error message */ $error_message = $error_message . "You must enter a valid password<br>"; $error_message = $error_message . "Valid passwords are min 5 characters and use letters, numbers and underscores only.<br>"; $error_message = $error_message . 'Your invalid password was: <font color="red">' . $_POST['password'] . "</font><hr>"; }else{ $password = trim($_POST['password']); } /* END validating password */ /* =============================================== */ /* =============================================== */ /* check to see if username is already taken */ $username = mysql_real_escape_string(trim($_POST['username'])); $query1 = "SELECT username from companies WHERE username = '$username'"; $result1 = mysql_query($query1) or die(mysql_error()); $count = mysql_num_rows($result1); if($count>0) { $error_message = $error_message . 'The username: <font color="red">' . $_POST['username'] . "</font> is taken.<hr>"; } /* =============================================== */ /* if any of the post variables are invalid */ /* set the session variable and send back to the form page */ if(strlen(trim($error_message))>0) { $_SESSION['error_message'] =$error_message; header("Location: register00.php"); exit(); } /* =============================================== */ $uploadDir = 'images/COMPANIES'; /* main picture folder */ $max_height = 450; /* largest height you allowed; 0 means any */ $max_width = 450; /* largest width you allowed; 0 means any */ $max_file = 2000000; /* set the max file size in bytes */ $image_overwrite = 1; /* 0 means overwite; 1 means new name */ /* add or delete allowed image types */ $allowed_type01 = array( "image/gif", "image/pjpeg", "image/jpeg", "image/png", "image/x-png", "image/jpg"); $do_thumb = 1; /* 1 make thumbnails; 0 means do NOT make */ $thumbDir = "/images/thumbs"; /* thumbnail folder */ $thumb_prefix = ""; /* prefix for thumbnails */ $thumb_width = 90; /* max thumb width */ $thumb_height = 70; // max thumb height //Writes the photo to the server if(move_uploaded_file($_FILES['upload']['tmp_name'], $target)) { /* HERE IS WHERE WE WILL DO THE ACTUAL RESIZING */ /* ============================================== */ /* ============================================== */ /* THESE SIX PARAMETERS MAY BE CHANGED TO SUIT YOUR NEEDS */ $o_path ="images/COMPANIES/"; $s_path = "images/thumbs/"; $file = $upload; $save = $file; $t_w = 200; $t_h = 150; /* ============================================== */ /* ============================================== */ /* DO NOT CHANGE THIS NEXT LINE */ Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path); //Tells you if its all ok /* ============================================== */ /* ============================================== */ /* PROVIDE A WAY FOR THEM TO GO SOMWHERE */ echo "The file ". $file . " has been uploaded, and your information has been added to the directory"; }else { //Gives and error if its not /* ============================================== */ /* ============================================== */ /* PROVIDE A WAY FOR THEM TO GO SOMWHERE */ echo "Sorry, there was a problem uploading your file."; } /* =============================================== */ /* PREPARE DATA FOR INSERTION INTO TABLE */ /* FUNCTION TO CREATE SALT */ function createSalt() { $string = md5(uniqid(rand(), true)); return substr($string, 0, 3); } //Writes the information to the database /* ============================================== */ /* ============================================== */ /* ALWAYS WRITE YOUR QUERIES AS STRINGS THAT WAY WHEN TESTING, YOU CAN MAKE SURE THAT THE VALUES CONTAIN WHAT YOU EXPECT */ $salt = createsalt(); $passwod = trim($_POST['password']); $hash = hash('sha256', $salt, $password); $approved = 0; $username = mysql_real_escape_string(trim($_POST['username'])); $email = mysql_real_escape_string(trim($_POST['email'])); $query ="INSERT INTO `companies` (company_name, contact_name, location, postcode, street1, street2, city, phone, email, basicpackage_description, premiumuser_description, password, salt, approved, upload) VALUES ('$company_name', '$contact_name', '$location', '$postcode', '$street1', '$street2', '$city', '$phone', '$email', '$basicpackage_description', '$premiumuser_description', '$password', '$salt', '$approved', '$upload')"; $result = mysql_query($query) or die(mysql_error()); /* =============================================== */ /* at this point we can send an email to the admin as well as the user. DO NOT send the user's password to ANYONE!!!! */ ?> Thank you for registering.<br>; Your account will be approved and activated within 24 hours.<br><br> Click here to return to the <a href="index.php">main page</a>. I'm very new to php and mysql so this might be a very stupid question and I'm apologizing ahead of time. Anyway I have a page titled Apparel.php that is supposed to show the most recent item uploaded from each of it's subpages. In other word Apparel is the $category and it has 4 $subcategories (Dresses.php, Skirts.php, Coats.php and Shorts.php). I was able to successfully have the right items show but my coding is pretty long, which I think may affect the speed of the page from loading. I'm sure there's a way to shorten it by perhaps using just one query but I can't figure out how. I'm actually using 4 queries but only posted 2 to keep it shorter. Thanks ahead of time! Code: [Select] <?php // Run a select query to get latest item from each subcategory $dynamicList = ""; $query1 = mysql_query("SELECT * FROM products WHERE category='Apparel' AND subcategory='Dresses' ORDER BY date_added DESC LIMIT 1"); $query2 = mysql_query("SELECT * FROM products WHERE category='Apparel' AND subcategory='Skirts' ORDER BY date_added DESC LIMIT 1"); $productCount = mysql_num_rows($query1); // count the output amount while($row = mysql_fetch_array($query1)){ $id = $row["id"]; $product_name = $row["product_name"]; $subcategory = $row["subcategory"]; $dynamicList .= ' <ul> <li><a href="Apparel/' . $subcategory . '.php"><img src="inventory_images/' . $id . '_1.jpg" alt="' . $product_name . '" width="140" height="210" border="0" /></a> <center><h3>' . $subcategory . '</h3></center> </li> </ul>'; } $productCount = mysql_num_rows($query2); // count the output amount while($row = mysql_fetch_array($query2)){ $id = $row["id"]; $product_name = $row["product_name"]; $subcategory = $row["subcategory"]; $dynamicList .= ' <ul> <li><a href="Apparel/' . $subcategory . '.php"><img src="inventory_images/' . $id . '_1.jpg" alt="' . $product_name . '" width="140" height="210" border="0" /></a> <center><h3>' . $subcategory . '</h3></center> </li> </ul>'; } mysql_close(); ?> MOD EDIT: [code] . . . [/code] BBCode tags added. Hi Guys, I'm hoping someone can find what I clearly cant see, I have a page meant to update database records, the page will load and populate with the existing data and allow 5 out of the 7 fields to be edited, however when editing any of those 5, the remaining 2 blank out and can't be filled in again. Im at a bit of loss and have been staring at it for a bit too long i think, hoping a fresh set of eyes can help. Here's the page (the fields I'm having issues with are inv1/inv2: <?php $page_title = 'Edit a Cart'; include ('style.html'); // Check for a valid ID, through GET or POST. if ( (isset($_GET['id'])) ) { // Accessed through active_search.php $id = $_GET['id']; } elseif ( (isset($_POST['id'])) ) { // Form has been submitted. $id = $_POST['id']; } else { // No valid ID, kill the script. echo '<div id="title">Page Error</div> <p class="error">This page has been accessed in error.</p><p><br /><br /></p>'; exit(); } require_once ('mysql_connect.php'); // Connect to the db. // Check if the form has been submitted. if (isset($_POST['submitted'])) { $errors = array(); // Initialize error array. // Check for a PO. { $po = trim($_POST['po']); } // Check for a Master Serial. { $sr = trim($_POST['serial']); } // Check for a Charger Serial. { $ch = trim($_POST['charger']); } // Check for a Battery Serial. { $bt1 = trim($_POST['battery1']); } // Check for a Battery Serial. { $bt2 = trim($_POST['battery2']); } // Check for a Inverter Serial. { $in1 = trim($_POST['inv1']); } // Check for a 2nd Inverter Serial. { $in2 = trim($_POST['inv2']); } // Check for a Radio Serial. { $abc = trim($_POST['abc']); } if (empty($errors)) { // If everything's OK. // Test for unique master serial. $query = "SELECT serial FROM serials WHERE serial='$id'"; $result = mysql_query($query); if (mysql_num_rows($result) == 1) { // Make the query. $query = "UPDATE serials SET po='$po', serial='$sr', charger='$ch', batt1='$bt1', batt2='$bt2', inv1='$in1', inv2='$in2', abc='$abc' WHERE serial='$id'"; $result = @mysql_query ($query); // Run the query. if (mysql_affected_rows() == 1) { // If it ran OK. // Print a message. echo '<div id="title">Success!</div> <p>The node has been edited.<a href="javascript:window.close();">Close</a></p><p><br /><br /></p>'; } else { // If it did not run OK. echo '<div id="title">System Error</div> <p class="error">The node could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message. echo '<p>' . mysql_error() . '<br /><br />Query: ' . $query . '</p>'; // Debugging message. exit(); } } else { // Already registered. echo '<div id="title">Error!</div> <p class="error">The Serial has already been registered.</p>'; } } else { // Report the errors. echo '<div id="title">Error!</div> <p class="error">The following error(s) occurred:<br />'; foreach ($errors as $msg) { // Print each error. echo " - $msg<br />\n"; } echo '</p><p>Please try again.</p><p><br /></p>'; } // End of if (empty($errors)) IF. } // End of submit conditional. // Always show the form. // Retrieve the user's information. $query = "SELECT * FROM serials WHERE serial='$id'"; $result = @mysql_query ($query); // Run the query. if (mysql_num_rows($result) == 1) { // Valid ID, show the form. // Get the user's information. $row = mysql_fetch_array ($result); // Create the form. echo '<div id="title">Edit a Cart</div> <form action="serial_edit.php" method="post"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td>P.O #:</td><td><input type="text" name="po" size="15" maxlength="15" value="' . $row['po'] . '" /></td> </tr> <tr> <td>Cart Serial:</td><td><input type="text" name="serial" size="15" maxlength="30" value="' . $row['serial'] . '" /></td> </tr> <tr> <td>Charger:</td><td><input type="text" name="charger" size="20" maxlength="40" value="' . $row['charger'] . '" /> </td> </tr> <tr> <td>Battery 1:</td><td><input type="text" name="battery1" size="20" maxlength="40" value="' . $row['batt1'] . '" /> </td> </tr> <tr> <td>Battery 2:</td><td><input type="text" name="battery2" size="20" maxlength="40" value="' . $row['batt2'] . '" /> </td> </tr> <tr> <td>Inverter 1:</td><td><input type="text" name="inverter1" size="20" maxlength="40" value="' . $row['inv1'] . '" /> </td> </tr> <tr> <td>Inverter 2:</td><td><input type="text" name="inverter2" size="20" maxlength="40" value="' . $row['inv2'] . '" /> </td> </tr> <tr> <td>ABC:</td><td><input type="text" name="abc" size="20" maxlength="40" value="' . $row['abc'] . '" /> </td> </tr> <tr> <td><input type="submit" name="submit" value="Submit" /><input type="hidden" name="submitted" value="TRUE" /></td> <td><input type="hidden" name="id" value="' . $id . '" /></td></tr> </form>'; } else { // Not a valid ID. echo '<div id="title">Page Error</div> <p class="error">This page has been accessed in error.</p><p><br /><br /></p>'; } mysql_close(); // Close the database connection. ?> Hi all
I want to display 5 records found in query and display by date order to most recent to todays date.
Any help most appreciated.
The php script below
<?php include 'c/config.php'; include 'c/library/opendb.php'; include 'c/library/timeFunctions.php'; include 'c/library/displayFunctions2.php'; $query = "SELECT * FROM events ORDER BY date,time"; $result = mysql_query($query); while($row = mysql_fetch_assoc($result)) { if ($row['date'] >= date('Y-m-d')) { displayEventsCurrent($row); } } include 'c/library/closedb.php'; ?> in database, I have faced error where query does not responded properly
it was showing the error message that "too much query, user cannot execute more query"....
when I increased the limit, it works for sometime and after sometime, it again generates the error , my question here is:
"why the error is occurring ?"
"what is the correct way to improve the execution of multiple queries at single instance ??? "
Hi, I am defining a php script to check captured input username and password from a form against a MySQL database and can't get the syntax right - regarding the $_POST['password'] portion of query. Here's the actual php code showing query: Code: [Select] //create and issue the query // $command = "SELECT username FROM agents WHERE username ='".$_POST['username']."';"; // THIS ONE WORKS JUST FINE IF JUST CHECKING USERNAME from DB $command = "SELECT username FROM agents WHERE username ='".$_POST['username']."' AND password = MD5('".$_POST['password']."');"; echo "Command: ".$command."<br>"; $result = mysql_query($command); echo "Result: ".$result."<br>"; Here's the error I get on the php page when loading and submitting username and password: Command: SELECT username FROM agents WHERE username ='user1' AND password = MD5('pass1234'); Result: Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/websited/public_html/projects/forgottenmobile/index.php on line 58 Note: line 58 is just checking for: Code: [Select] mysql_num_rows($result) == 1; The issue is the query is not correct regarding: password = MD5('pass1234') portion of the SQL string. I know it's with the location of th single and double quotes but struggling to find the right syntax structure. Can someone advise the correct syntax structure to include MD5 function for the variable '$_POST[password]' in the $command query? --- Note: the password is encrypted using MD5 so that function required in the query. thanks! Alright so I have a database table of users set up that creates a unique member_id for each new registered user. I then have a second table that stores data entries that also has a member_id field. When the users are logged in, they can enter a new entry into this second table. The problem I'm having is that when the entry is written into the database, the member_id field always comes up as "0." I'm using the session variables to pass the member_id to the query. Here's the code: //Create Member Session Variables $memberID = $_SESSION['SESS_MEMBER_ID']; //Create INSERT query $qry = "INSERT INTO userBars(member_id, barName, barAddress, barCity, barState, barZip) VALUES('$memberID','$ename','$street','$city','$state','$zipcode')"; $result = @mysql_query($qry); //Check whether the query was successful or not if($result) { header("location: register-success.php"); exit(); }else { die("Query failed"); } When I echo the $memberID var I do in fact get the member_id, but when this script writes into the database, the member_id field is always set to "0." Anyone have any ideas as to why this might happen? I've actually ported the query below from something else I've done that works. Not sure what I'm missing.
Here are the errors I'm getting: Quote
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home2/csi/public_html/resources/preview1920/functions.php on line 9
$query = "SELECT id FROM a_sectionals_bkb"; $results = mysqli_query($con,$query); //=> Line 9 echo mysqli_error($results); //=> Line 11 echo '<div class="sectional_select">'; echo '<form name="Sectionals">'; echo '<select name="sectional" size="3" onChange="go()">'; echo '<option value="NULL">Select Sectional</option>'; while($row = mysqli_fetch_assoc($results)) { echo '<option value="/season-preview/19-20/sectional1920/?sectional='. $row['id'] .'">Sectional '. $row['id'].'</option>'; } echo '</select>'; // End Sectional Select echo '</div>'; // End of Sectional Select Function
Hi there, im looking for a little bit of help, could someone who knows how to use REXEXP properly tell me how i would select only the uppercase titles from title column and display them Code: [Select] +------------+-----------+ | id | title | +------------+-----------+ | 1 | one | | 2 | TWO | | 3 | three | | 4 | FOUR | +------------+-----------+ Code: [Select] <?php $username="user"; $password="pw"; $database="db"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query = "SELECT title FROM template WHERE name REGEXP '^(A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z)'"; $result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "Custom Template Name : {$row['title']} <br><br>"; } mysql_close(); ?> This was an attempt i made but it did not work i got the following error: Quote Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\ProgramData\xampp\htdocs\test.php on line 14 I did attempt to do a search on it but if im honest i didnt fully understand what they were saying. Im using php 5.3.5 and mysql 5.5.8 Thanks for your help Hi All, Just a couple of things with my site search, I am having trouble getting the search results to pickup any and all keywords. For example, if keywords for a search result are listed in the keywords column of my db as 'one, two, three' a search query for 'one two' is fine but a search for 'one three' will not display the search result. Instead of treating the keywords seperately it is treating all keywords as a whole phrase. How can I make the search results pickup any keyword regardless of order. Secondly I'm having trouble getting the search results to display by keyword relevance, any help is greatly appreciated. Thanks. Code: [Select] function search() { parent::Controller(); $this->load->model('Templating'); $this->load->model('Company'); } function index() { $this->load->view('search'); } function search_redirect() { if ($_POST['keyword'] == '') $_POST['keyword'] = 'Keyword'; redirect('search/showlist/'. urlencode(underscore($_POST['location'])).'/'. urlencode(underscore($_POST['category'])).'/'. urlencode(underscore($_POST['keyword']))); } function showlist($location = 'any', $category = 'any', $keyword = 'keyword', $offset = '0') { /* get results */ $data['companies'] = $this->Company->search($keyword, $category, $location, $offset, $name); /* paginate results */ $row = $data['companies']->row(); if($keyword == 'keyword' and $category=='any' ) { $data['categoryList'] = $this->buildCategoryList($location); } elseif(isset($row->categoryId)) { $categoryId = $row->categoryId; $data['linkList'] = $this->buildRefineList($categoryId); } $this->load->library('pagination'); $config['base_url'] = site_url().'search/showlist/'.$location.'/'.$category.'/'.$keyword.'/'; $config['total_rows'] = $this->Company->total_companies; $config['per_page'] = $this->Company->per_page; $config['num_links'] = 3; $config['uri_segment'] = $this->uri->total_segments(); $this->pagination->initialize($config); $data['pagination'] = $this->pagination->create_links(); $data['logged_in'] = $this->session->userdata('logged_in'); $data['company_id'] = $this->session->userdata('company_id'); $data['search_category'] = $category; $data['search_location'] = $location; if ($this->session->userdata('admin') != ''){ $data['admin'] = $this->session->userdata('admin'); } /* initialise template settings */ $center = 'center/list_companies'; $this->load->vars($data); $this->Templating->show($center); } I'm having a few issues with a serach function in Internet Explorer, it works fine in firefox which is very annoying. What basically is happening, is the a form is sumbitting and posting info across, but on itself and then this is transfered into a php variable which is used on the query. Default values have been assigned if the isset of the form is not true. So I believe the issue is occuring on the " if(isset($_POST['submit'])) " but as stated it works perfectly fine in firefox. Any suggestions? Code: [Select] <?php print " <form target='_self' method='POST'> <table class=''> <tr> <td> <input name='vehicle' type='text' id='search_name' size='16'> <input type='image' src='images/search.gif' alt='Search' name='submit' id='search' value='Search'/> </td> </tr> <tr> <td> <select name='filter' id='filter'> <option value='make' selected='selected'>Filter By</option> <option value='make'>Vehicle Manufacture</option> <option value='model'>Vehicle Model</option> <option value='our_price'>Price</option> <option value='delivery_time'>Delivery Time</option> </select> </td> </tr> <tr> <td> <input type='radio' name='direction' value='ASC' checked/>Ascending <input type='radio' name='direction' value='DESC' />Descending </td> </tr> </form> "; include "connections/dbconnect.php"; if(isset($_POST['submit'])) { $vehicle = $_POST['vehicle']; $filter = $_POST['filter']; $direction = $_POST['direction']; //$rowsPerPage = $_POST['limit']; } else { $filter = "make"; $direction = "ASC"; } //$manfactures = "Ford"; if(isset($_GET['limit'])) { $rowsPerPage = $_GET['limit'];; } else { // how many rows to show per page $rowsPerPage = 10; } // by default we show first page $pageNum = 1; // if $_GET['page'] defined, use it as page number if(isset($_GET['page'])) { $pageNum = $_GET['page']; } // counting the offset $offset = ($pageNum - 1) * $rowsPerPage; $car_query = " SELECT * FROM cars WHERE model LIKE '%$vehicle%' OR make LIKE '%$vehicle%' OR model_details LIKE '%$vehicle%' OR search LIKE '%$vehicle%' ORDER BY $filter $direction LIMIT $offset, $rowsPerPage"; $car_result = mysql_query($car_query) or die ("Error in query: $car_query. ".mysql_error()); setlocale(LC_MONETARY, 'en_GB'); $fmt = '%i'; // how many rows we have in database $query = "SELECT COUNT(model) AS numrows FROM cars"; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_array($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); // print the link to access each page $self = $_SERVER['PHP_SELF']; $nav = ''; for($page = 1; $page <= $maxPage; $page++) { if ($page == $pageNum) { $nav .= " $page "; // no need to create a link to current page } else { $nav .= " <a href=\"$self?page=$page&limit=$rowsPerPage\">$page</a> "; } } if ($pageNum > 1) { $page = $pageNum - 1; $prev = " <a href=\"$self?page=$page&limit=$rowsPerPage\">[Prev]</a> "; $first = " <a href=\"$self?page=1&limit=$rowsPerPage\">[First Page]</a> "; } else { $prev = ' '; // we're on page one, don't print previous link $first = ' '; // nor the first page link } if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = " <a href=\"$self?page=$page&limit=$rowsPerPage\">[Next]</a> "; $last = " <a href=\"$self?page=$maxPage&limit=$rowsPerPage\">[Last Page]</a> "; } else { $next = ' '; // we're on the last page, don't print next link $last = ' '; // nor the last page link } if (mysql_num_rows($car_result) > 0) { ...... bringing back all the information from the database Hi I have a 4 button navigation, home, projects, about and contact. This is in one table, menu, this table has the relevant icon to display with the appropriate link and another field is the link itself, ?page=home. Menu is joined with the pages table using the following query SELECT * FROM menu LEFT JOIN pages ON menu.id = pages.page_id When I run this through phpmyadmin sql console everything is returned as expected, all pages match up with the navigation. When I print_r($row); all 4 fields from the nav table and all 7 fields from the pages table, totalling 11 fields, display as per the query running in phpmyadmin which was as expected however, on the actual page it isn't going as hoped and expected. I have
/* query for page data(navigation & title) */
$sql= "SELECT * FROM menu LEFT JOIN pages ON menu.id = pages.page_id"; $stmt = $db->query($sql); $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
<?php echo $row['header']; ?>
*/ echo "<pre>"; print_r($row); echo "</pre>";
$row = $stmt->fetch(PDO::FETCH_ASSOC);
The php used for the navigation is
<?php echo $row['url']; ?> <?php echo $row['icon']; ?> <?php echo $row['header']; ?>
<a href="<?php echo $row['url']; ?>"><i class="<?php echo $row['icon']; ?>"></i> <?php echo $row['header']; ?></a>
As I know the SQL is working I realise I have made an error in the PHP but cannot work out what. As far as I can see I should be using fetch, rather than fetchAll, so as to only return 1 record as requested via the navigation links however fetchAll would give me the data required for the navigation to be labelled correctly. I cannot work out where I am going wrong. Any help would be appreciated.
Edited October 31, 2020 by Skorpio Update with further information hi i have the script below which copies data from one table to another but will only insert new data update current data or delete old data from tempproducts to products then it will delete the tempproducts from the db however i keep getting this error: Warning: mssql_query() [function.mssql-query]: Query failed in E:\UpdateProducts.php on line 33 updateproducts.php Code: [Select] <?php include('../../otherscripts/functions.php'); $log = new Logging(); // create DB connection $host = "localhost"; $user = "user"; $pass = "pass"; $mydb = "db"; $db = mssql_connect($host,$user,$pass); //Select Database mssql_select_db($mydb); // delete all old data $sql0 = "SELECT * FROM tempproduct"; $sql1 = "INSERT INTO products SELECT * FROM tempproduct WHERE manf_part_no NOT IN (SELECT manf_part_no FROM products) AND supp_id NOT IN (SELECT supp_id FROM products)"; $sql2 = "DELETE FROM products WHERE manf_part_no NOT IN (SELECT manf_part_no FROM tempproduct) AND supp_id NOT IN (SELECT supp_id FROM tempproduct)"; $sql3 = "UPDATE p1 SET p1.avail_qty = t1.avail_qty, p1.cost_price = t1.cost_price, p1.rrp = t1.rrp, p1.date_added = t1.date_added, p1.description = t1.description FROM Products p1 INNER JOIN tempproduct t1 ON (p1.manf_part_no = t1.manf_part_no AND p1.supp_id = t1.supp_id)"; $sql4 = "TRUNCATE TABLE tempproduct"; //If tempproduct is empty done Execute Commands if it is full then execute commands $query = mssql_query($sql0) or die($log->lwrite('Failed to select for count from db')); $rowcount = mssql_num_rows($query); if($rowcount == 0){ $log->lwrite('Teh tempproduct am emptyish'); } else{ mssql_query($sql1) or die($log->lwrite('Failed to insert to db'.$sql1)); mssql_query($sql2) or die($log->lwrite('Failed to Delete from db')); mssql_query($sql3) or die($log->lwrite('Failed to Update db')); mssql_query($sql4) or die ($log->lwrite('Failed to TRUNCATE db')); } ?> if i run $sql1 command in the sql manager it runs fine and no errors occur? |