PHP - Running Mysql Query In Php
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>'; } ?> Similar TutorialsHi 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. Hey 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 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.'; } } ?> 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; } }```
My my.cnf file has three sections (mysqld, mysqld_safe, mysql). It seems that they represent different modes which MySQL runs in. Is this correct? I read that some recommend running in safe mode. Should I be if it is being used to support PHP? I typically start MySQL as "service mysqld start" when running Centos. How should I be starting it if I want it in safe mode. Hey, I am a bit of a noob at php/mysql and trying to be clever(emphasis on trying). I want to pull some php/html code from a database in mysql, whilst it does display the html, the php does not. Can this even be done? Is it going to cause me issues later on? Code: [Select] [php] <?php $query = "SELECT * FROM pages"; $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($result)){ $body = $row["body"]; echo $body; }?> [/php] Any help would really be appreciated. Ell I am trying to create a calendar of Events for my company's website. When I search for this type of calendar, I can find code that runs the calendar from one Events table. However, we could have an Event that has multiple performances. (For example, Lily Tomlin could be performing at the Atwood Concert Hall in Anchorage on 09/09/11 and at the Vagabond Blues in Palmer on 09/10/11.) So we have two tables to draw the information from: Events and Performance I can successfully create a MySQL query (see below) with PHP coding that will make a listing (as demostrated on our website http://www.centertix.net/). Code: [Select] "SELECT Events.PublishDate, Events.EventOnSaleDate, Events.BldgContractDate, Events.SetUpComplete, Events.EventTitle, Performance.PerfID, Performance.startDateTime, Performance.endDateTime, Performance.PerfType, venues.VenueName, venues.VenueCode FROM (Performance RIGHT JOIN Events ON Performance.EventID = Events.EventID) LEFT JOIN venues ON Performance.VenueCode = venues.VenueCode WHERE Events.BldgContractDate Is Not Null AND Events.SetUpComplete Is Not Null AND Performance.PerfType='Public Event'"However, I'm not advanced enough to create the if-clause or while-loop to check to see if the Performance.startDate = the calendar's date and then place the info into the appropriate calendar grid box. I think have determined where it should be place in my PHP code, but need help getting the calendar to work. Here's the code where I think it should go: Code: [Select] for($list_day = 1; $list_day <= $days_in_month; $list_day++): if(($list_day == date("j",mktime(0,0,0,$this->month))) && (date("F") == date("F",mktime(0,0,0,$this->month))) && (date("Y") == date("Y",mktime(0,0,0,$this->month,$list_day,$this->year)))) { $this->calendar.= '<td class="'. $this->style .'-current-day">'; } else { if(($running_day == "0") || ($running_day == "6")) { $this->calendar.= '<td class="'. $this->style .'-weekend-day">'; } else { $this->calendar.= '<td class="'. $this->style .'-day">'; } } /* add in the day number */ $this->calendar.= '<div class="'. $this->style .'-day-number">'.$list_day.'</div>'; /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/ $this->calendar.= '<div class="'. $this->style .'-text"><a href="">PERFORMANCE INFO</a></div>'. "\n"; /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF NO MATCHES FOUND, PRINT NOTHING !! **/ $this->calendar.= str_repeat('<p> </p>',2); $this->calendar.= '</td>'; if($running_day == 6): $this->calendar.= '</tr>'; if(($day_counter+1) != $days_in_month): $this->calendar.= '<tr class="'. $this->style .'-row">'; endif; $running_day = -1; $days_in_this_week = 0; endif; $days_in_this_week++; $running_day++; $day_counter++; endfor; Please help me plug the calendar in with the appropriate events! If you would like to see how far I have gotten, you can check out this link: http://www.myalaskacenter.com/calendars/calendarSample2.php Here is my code: // Start MySQL Query for Records $query = "SELECT codes_update_no_join_1b" . "SET orig_code_1 = new_code_1, orig_code_2 = new_code_2" . "WHERE concat(orig_code_1, orig_code_2) = concat(old_code_1, old_code_2)"; $results = mysql_query($query) or die(mysql_error()); // End MySQL Query for Records This query runs perfectly fine when run direct as SQL in phpMyAdmin, but throws this error when running in my script??? Why is this??? Code: [Select] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= new_code_1, orig_code_2 = new_code_2WHERE concat(orig_code_1, orig_c' at line 1 If you also have any feedback on my code, please do tell me. I wish to improve my coding base. Basically when you fill out the register form, it will check for data, then execute the insert query. But for some reason, the query will NOT insert into the database. In the following code below, I left out the field ID. Doesn't work with it anyways, and I'm not sure it makes a difference. Code: Code: [Select] mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); Full code: Code: [Select] <?php include_once("includes/config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><? $title; ?></title> <meta http-equiv="Content-Language" content="English" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> </head> <body> <div id="wrap"> <div id="header"> <h1><? $title; ?></h1> <h2><? $description; ?></h2> </div> <? include_once("includes/navigation.php"); ?> <div id="content"> <div id="right"> <h2>Create</h2> <div id="artlicles"> <?php if(!$_SESSION['user']) { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $name = mysql_real_escape_string($_POST['name']); $server_type = mysql_real_escape_string($_POST['type']); $description = mysql_real_escape_string($_POST['description']); if(!$username || !$password || !$server_type || !$description || !$name) { echo "Note: Descriptions allow HTML. Any abuse of this will result in an IP and account ban. No warnings!<br/>All forms are required to be filled out.<br><form action='create.php' method='POST'><table><tr><td>Username</td><td><input type='text' name='username'></td></tr><tr><td>Password</td><td><input type='password' name='password'></td></tr>"; echo "<tr><td>Sever Name</td><td><input type='text' name='name' maxlength='35'></td></tr><tr><td>Type of Server</td><td><select name='type'> <option value='Any'>Any</option> <option value='PvP'>PvP</option> <option value='Creative'>Creative</option> <option value='Survival'>Survival</option> <option value='Roleplay'>RolePlay</option> </select></td></tr> <tr><td>Description</td><td><textarea maxlength='1500' rows='18' cols='40' name='description'></textarea></td></tr>"; echo "<tr><td>Submit</td><td><input type='submit'></td></tr></table></form>"; } elseif(strlen($password) < 8) { echo "Password needs to be higher than 8 characters!"; } elseif(strlen($username) > 13) { echo "Username can't be greater than 13 characters!"; } else { $check1 = mysql_query("SELECT username,name FROM servers WHERE username = '$username' OR name = '$name' LIMIT 1"); if(mysql_num_rows($check1) < 0) { echo "Sorry, there is already an account with this username and/or server name!"; } else { $ip = $_SERVER['REMOTE_ADDR']; mysql_query("INSERT INTO servers (username, password, name, type, description, ip, votes, beta) VALUES ($username, $password, $name, $server_type, $description, $ip, 0, 1)"); echo "Server has been succesfully created!"; } } } else { echo "You are currently logged in!"; } ?> </div> </div> <div style="clear: both;"> </div> </div> <div id="footer"> <a href="http://www.templatesold.com/" target="_blank">Website Templates</a> by <a href="http://www.free-css-templates.com/" target="_blank">Free CSS Templates</a> - Site Copyright MCTop </div> </div> </body> </html> I am creating a site to display some products. For ease of updating I want it to run off a MySQL database. I have created the database and php scripts to output and input data etc. I know want to show that data in my web pages. My question is.... Is it best to insert HTML into the php output script to display the information and make the site look how I want....OR ....... should I create a template of the site in HTML and then somehow call the php output script (and the particular row of the database...) Basically... should I put the html code into the php - OR - put the php into the HTML?? I hope this make sense...... thanks I'm restarting this under a new subject b/c I learned some things after I initially posted and the subject heading is no longer accurate. What would cause this behavior - when I populate session vars from a MYSQL query, they stick, if I populate them from an MSSQL query, they drop. It doesn't matter if I get to the next page using a header redirect or a form submit. I have two session vars I'm loading from a MYSQL query and they remain, the two loaded from MSSQL disappear. I have confirmed that all four session vars are loading ok initially and I can echo them out to the page, but when the application moves to next page via redirect or form submit, the two vars loaded from MSSQL are empty. Any ideas? Hi All, Wondered if someone could help me out with a sql query that I am having difficulty with? My database consists of 3 tables, clients, video, category. The video table stores the primary key value of the clients table and the category table as a foreign key. What I am trying to achieve is return all the videos that are associated to a particular client and group them under the relevant category. If there are now videos that match the category then I do not want to display the category. Here is my code so far: Code: [Select] <?php $sql = "SELECT category.cat_id, category.name AS catname FROM category"; $result = mysql_query($sql) or die (mysql_error()); while($categoryrow = mysql_fetch_assoc($result)) { ?> </p> <div class="themeheader"><h5><?php echo $categoryrow['catname']; ?></h5></div> <Br /> <?php $vsql = "SELECT video.video_id, video.title, video.description, video.thumbnail FROM video WHERE video.cat_id = '" . $categoryrow['cat_id'] . "' AND video.client_id = $customerid ORDER BY video.video_id DESC"; $vresult = mysql_query($vsql) or die (mysql_error()); ?> <div class="videos"> <ul> <?php while($videorow = mysql_fetch_assoc($vresult)) { ?> <li id="categoryList"><a href="film-details.php?video_id=<?php echo $videorow['video_id']; ?>"><img src="+_1m4g35/<?php echo $videorow['thumbnail']; ?>" alt="<?php echo $videorow['title']; ?>" title="<?php echo $videorow['title']; ?>" width="291" height="142" border="0" /></a> <h2><?php echo $videorow['title']; ?></h2> <p><?php $limit = 100; if (strlen($videorow['description']) > $limit) $description = substr($videorow['description'], 0, strrpos(substr($videorow['description'], 0, $limit), ' ')) . '... <a href="film-details.php?video_id='.$videorow['video_id'].'">read more</a>'; echo $description; ?> </p> <?php } //end video loop?> </ul> <br class="clearfloat" /> </div> <?php } //end category loop ?> </div> The above code is the closest I have got but it still outputs the categories even when there are no videos that match the category id and the client id. Any help in the right direction gratefully received as I am gradually going insane! I have a query which when I run in phpmyadmin it returns the results I want. When I put it into PHP I get no results can someone tell me what I'm doing wrong? Code: [Select] <?php include("config.php"); ?> <?php // sending query $sql = mysql_query("SELECT dayname((date(FROM_UNIXTIME(dateline)))) as 'Day Of Week', date((date(FROM_UNIXTIME(dateline)))) as 'Date', count(*) as 'Number of Opened Tickets', ( select count(ticketmaskid) from swtickets where date(FROM_UNIXTIME(swtickets.lastactivity)) = Date and isresolved=1 ) as 'Number of Closed Tickets' from swtickets where ((date(FROM_UNIXTIME(dateline)) between (DATE_SUB(CURDATE(), INTERVAL (IF(DAYOFWEEK(CURDATE())=1, 9, DAYOFWEEK(CURDATE()))) DAY)) and (DATE_ADD(CURDATE(), INTERVAL (6 - IF(DAYOFWEEK(CURDATE())=1, 8, DAYOFWEEK(CURDATE()))) DAY)) )) group by date(FROM_UNIXTIME(dateline))"); ?> <?php echo $sql; ?> All it returns is: Resource id #4 When in phpmyadmin I get: Hello! Please help... I am trying to use the script below to get results from a mysql database based on a query of the form fields (the names of which are displayed near the top of the script as POST items) When a location or age etc. is entered into the form, I want the script to search for records which meet those criteria. At the moment the script works but only does so if all the values are entered to match what is in the database. e.g. if the location england and the age 22 was entered into the form, and that matched the value in the database, then at the moment, the script will display the result, but if only the location is entered in the form without any value for age/genre etc. then no results are displayed. Any help would be very welcome as I have search high and low for a solution on google... which doesn't seem to exist... I'm not that experienced with php/mysql but am learning on the job so any helpful prompts as to terms etc. would help! Thanks! Lewis <?php if($_POST) { $searchage = $_POST['searchage']; $searchlocation = $_POST['searchlocation']; $searchgenre = $_POST['searchgenre']; $searchinstrument = $_POST['searchinstrument']; $searchexperience = $_POST['searchexperience']; // Connects to your Database mysql_connect("localhost", "user", "pass") or die(mysql_error()); mysql_select_db("DB") or die(mysql_error()); $query = mysql_query("SELECT * FROM table_user WHERE userage = '".$searchage."' AND userlocation = '".$searchlocation."' AND usergenre = '".$searchgenre."' AND userinstrument = '".$searchinstrument."' AND userexperience = '".$searchexperience."'") or die(mysql_error()); $num = mysql_num_rows($query); echo "$num results found!<br>"; while($result = mysql_fetch_assoc($query)) { $username = $result['username']; $useremail = $result['useremail']; $userage = $result['userage']; $userlocation = $result['userlocation']; $usergenre = $result['usergenre']; $userinstrument = $result['userinstrument']; $userexperience = $result['userexperience']; $userbiography = $result['userbiography']; echo " Name: $username<br> Email: $useremail<br> Age: $userage<br> Location: $userlocation<br> Gen $usergenre<br> Instrument: $userinstrument<br> Experience: $userexperience<br> Biography: $userbiography<br><br> "; } } ?> Hi
I need a sql query help from you guys.
It is a sql query for get all upline referrer details from database for particular person
when new person register his details are storing in wp_members_tbl with uername, password, firstname, lastname, email, phone, address, referrer etc.
Below the query is for user
$wp_aff_members_db = $wpdb->get_row("SELECT * FROM $members_table_name WHERE refid = '".$_SESSION['user_id']."'", OBJECT);
And below the query is for this user's upline referrer
$wp_aff_members_db = $wpdb->get_row("SELECT * FROM $members_table_name WHERE refid = '$referrer'", OBJECT);
Now i need the query for find and get this referrer's upline referrer.
Please help me with a solution
Regards
Edited by rajasekaran1965, 23 October 2014 - 10:09 AM. Query whats wrong with this query? $queryreg = mysql_query("UPDATE application SET employer = '$employer' AND eaddy = '$employer_address' AND ecity = '$employer_city' AND estate = '$employer_state' and ezip = '$employer_zip' AND supervisor = '$employer_supervisor' WHERE appID = '$appID'") or die(mysql_error()); I can't figure it out. Hello, I have a query where i try to search, but i want to put a limitation, but it doesn't seems to be working :/ Here's my code: $result = mysql_query("SELECT * FROM clients WHERE staff = 0 AND username LIKE '%" . $keyword . "%' OR company LIKE '%" . $keyword . "%' ORcontact LIKE '%" . $keyword . "%' OR address LIKE '%" . $keyword . "%' OR email LIKE '%" . $keyword . "%' OR phone LIKE '%" . $keyword . "%' ORDER BY phone"); Alright, so i basically want the user to search in all of those fields, however i want it to filter all "staff" members, so it should only view the "0" ones, meaning the clients, only problem that when i run this, all clients gets displayed, also the staff accounts. Any suggestion? I am creating a site that has to display 36 images on the screen. The image name is stored in the database. My problem is if I have less than 36 images stored I need to display a default image. here is my current query $sql="SELECT col_image, col_url from tbl_images WHERE col_active='1' and col_bigimage='0' ORDER BY RAND() limit 36"; so If I only have 20 active images. I need to display 16 default images. I hope this makes sense. Bill |