PHP - Double Running Query?!
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.'; } } ?> 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? 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."; } } 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'm so sorry for this question but I not really know how to play with single and double quote. If I have a query like this: Code: [Select] mysql_query('UPDATE table SET Status=1,Sending=Done WHERE ID IN ('.implode(',', $done).')'); And I wish to add Code: [Select] SentAt='$date' in the query as well , and I try this: Code: [Select] mysql_query('UPDATE table SET Status=1,Sending=Done,SentAt='$date' WHERE ID IN ('.implode(',', $done).')'); Not working...how should I write it? Thank you. 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. Can someone please tell me what i have got wrong here? I am trying to return value C if conditions a AND B are met or return value D. Not sure if its parenthesis or something else? <?php if (($row_Recordset4['multidirection']=="yes") && ($_POST["widthcheck"] < $row_Recordset4['drop'])) echo $row_Recordset4['width'];else echo $row_Recordset4['drop'] ?> Thanks if u use this for one condition if ($nr > 5) how would u check if the nr is between 5 and 50 thanks ! This is strange.. I have the following code that checks if there is currently a cap set on requests. Code: [Select] $result = mysql_query("SELECT cap FROM requests"); while($data = mysql_fetch_array($result)) { if ($data['cap'] == '1') { echo"<h1>Requests are currently disabled at this time.</h1>"; }else{ echo'<h1><a href="requestlivery.php">Request Livery</a> | <a href="requestlogo.php">Request Logo</a></h1>'; } } For some reason, this: <h1><a href="requestlivery.php">Request Livery</a> | <a href="requestlogo.php">Request Logo</a></h1> is printed out twice on the webpage. Like: Request Livery | Request LogoRequest Livery | Request Logo I even put that code on a brand new blank page, and it does the same thing. Any ideas as to why would it do that? Unk sorry, I posted twice. Why is double spacing the results I know it's stupid simple but I can't see it. I removed $host ip so if you test put one in there. <!doctype html> <html lang="en"> <html> <body> <?php ini_set('max_execution_time', 0); ini_set('memory_limit', -1); $host = "insert IP"; $ports = array(21 ,22 ,23 ,25, 80, 81, 110, 143, 443, 587, 2525, 3306); foreach ($ports as $port) { $connection = @fsockopen($host, $port, $errno, $errstr, 2); if (is_resource($connection)) { echo '<p>' . $host . ':' . $port . ' ' . '(' . getservbyport($port, 'tcp') . ') is open.</p>'; fclose($connection); } else { echo '<p>' . $host . ':' . $port . ' is not Open.</p>'; } } ?> </body> </html>
please help me with this.since i started posting this form to its self it has been inserting values twice into the database when the user clicks submit button and i also noticed that i have to refresh the page before inserted comments can be showed.this is my code: Code: [Select] <?php include"header.php"; $sql="SELECT post_content,post_by FROM post WHERE topicsID='$tpid'"; $result=mysql_query($sql)or die(mysql_error()); while($row=mysql_fetch_array($result)) { echo"<strong>{$row['post_by']}</strong>: {$row['post_content']}"."</br>"; } ?></td> </tr> </table> <?php include"header.php"; if(isset($_POST['submit'])) { $comment=mysql_real_escape_string(trim($_POST['comment'])); $name=mysql_real_escape_string(trim($_POST['name'])); $hidden=$_POST['id']; if($comment!=='' && $name!=='') { $topicid=$_GET['id']; $ins="INSERT INTO post(post_content,post_by,post_id)VALUES('$comment','$name','$topicid')"; mysql_query($ins) or die(mysql_error()); } else { echo"you cannot post an empty field"; } } ?> <h3>Post your comments here</h3> <form action=''method='post'> <textarea name="comment" id="content" style="width:400px;height:50px;background-color:#D0F18F;color:#000000;font:15px/20px cursive;scrollbar-base-color:#638E0D;"></textarea> <br /> Name:<input type="text"name="name"/> <input class="button" type="submit"name="submit"value="submit" /> </p> </form> Hey guys i need to generate a table for a multilevel marketing simulation of 10.000 members. It's a bi-level. All i need is a table with id, parrent I am lost with the double loop ... I'm designing a website that takes user input from in a <textarea></textarea> and enters the input into a database. Everything works besides if the user has double quotes (") in his/her message. (the name of the table that I want to add to is alluserposts) What i have so far is the following: from index.php: <form action="insert2.php" method="post"><textarea name="user_post" rows="6" cols="35"></textarea></form> from insert2.php: mysql_query("INSERT INTO alluserposts (post_value) VALUES(" . "\"" . $_POST['user_post'] . "\")" ,$db) or die(mysql_error($db)); I want the user to be able to input any character. How can i do that? I have a problem which is why I am here. What I am trying to achieve I am creating a very very basic timetabling system online, using php and sql. I am still in the process of completing it and changing bits from here to there. Although I am fully aware that the current design / implementation needs several changes and amendments, but however it performs most of the basic functionalities from a login system to the ability to add data delete data and also reset the database and recreate. The problem I have a table called tCourse althouogh a full ERD implementation has not taken place, it is still trial and error period. The table consists of the following: - Course - Unit - Course_Code - Year (i.e. Yr1, Yr2, Yr3) - Credits (Value of the unit) - Day - Semester - Start_Time - End_Time - Room - Tutor At the moment the primary keys for the table a - Day - Start_Time - Room_ - Semester This basically prevents a particular day, a semester, a room having been booked at the same time. Which for a very basic one is ok. The only problem is though, if someone books for example: Monday >> 13:00:00 To 14:00:00 >> 205 >> Sem1 (ok) Monday >> 13:00:00 To 14:00:00 >> 205 >> Sem1 (Not ok, which is good, as it is a repeat and prevents double booking) However the problem comes he Monday >> 12:00:00 To 14:00:00 >> 205 >> Sem1 (ok) So this is allowing a booking even though that room will be busy i.e. booked between 13:00 to 14:00 So is there a way I can limit it, so if there is a room booked for that particular period it will not do it. I have done a bit of research and friend's have suggested doind several for loops and quering the database beforehand. I came here, mainly because there are a lot of experienced individuals here whom may have a simpler solution, although I can understand it won't be a one liner . I would appreciate any help, if not, it is still ok. I am wondering since in php when you write string in " " quotes php will look if there is any variable and if it is it will read that variable and replace variable name with that value inside the string. However when i use ' ' quotes php will not look for any variables inside that string. So my question is when you write a really big application is it good to always use ' ' quotes when you can instead of " " ones. Does that have an impact on performance. Thanks Hello, I am just trying to learn new stuff about php so I was trying to rebuild the function that sets $_GET['name']. I got it to work with only one "?name=value" but im having trouble setting the multi name=value&name2=value2 What I want it to do is the same that I have done with a single variable Here is the code I have so far: Code: [Select] <?php # Creating the get function get(); echo $_GET['username']; function get() { $queries = $_SERVER['QUERY_STRING']; $check_for_multiples = strpos($queries, "&"); $t1 = substr_count($text, '&'); if($t1 > 0) { $total_variables = add($t1, 1); } else { $total_variables = $t1; } $del1 = "&"; $del2 = "="; if($check_for_multiples > 0) { $array1 = explode("$del1", $queries); foreach($array1 as $key=>$value) { $array2 = explode("$del2", $value); foreach($array2 as $key2=>$value2) { $array3[] = $value2; } } $afinal = array(); for ( $i = 0; $i <= count($array3); $i += 2) { if($array3[$i]!="") { $afinal[trim($array3[$i])] = trim($array3[$i+1]); echo $afinal[$i]; } } } if($check_for_multiples <= 0) { $queries = explode("=", $queries); #echo "VAR=".$queries[0]." VALUE=".$queries[1].""; $_GET[''.$queries[0].''] = $queries[1]; } } function add($a, $b) { $answer = $a + $b; return $answer; } function subtract($a, $b) { $answer = $a - $b; return $answer; } function multiply($a, $b) { $answer = $a * $b; return $answer; } function divide($a, $b) { $answer = $a / $b; return $answer; } same(this.getParams['vb'], ab.fill(), 'vb test');Expected: false Result: "false" Diff: false "false" Please tell me how to fix this problem. How do I apply double delete verification? Right now I have... Code: [Select] if (isset($_POST['delete'])) { if(is_array($_POST['delete'])) { $keys = array_keys($_POST['delete']); $id = $keys[0]; $sql = "DELETE FROM `blog_posts` WHERE `post_id` = '$id'"; header("Location: " . $_SERVER['php_self'] . "?" . $_SERVER['query_string'] ); } } if(isset($sql) && !empty($sql)) { mysql_query($sql) or die(mysql_error()); } which deletes the query great, but I want some box to pop up saying, are you sure you want to delete this post? I'm not sure how to create this verification. |