PHP - Query Builder Reports
Have you guys ever build a smart queries for users too generate reports basically on anything they may want. I am looking on making something very user friendly. I do not have any ideas where to start
Similar TutorialsI am setting up a site that is using MODx 2.2 Revolution. I had been using ValidForm Builder as my contact form generator and have used it for a while and really like it. One of the things I liked about MODx is that I was not tied to strictly using their plugins and so forth and that its generally pretty easy to integrate php code into the site via what they call snippets. Anyway, Im sure many here are familiar with MODx. However, the issue I am having is getting ValidForm to work in MODx. When you make a 'snippet' in MODx, it has to have a return. I have posted the code for a sample form below from the ValidForm Builder website. I created a snippet and added the below code to it to test things out. Knowing that the snipped had to have a return, I tried return ($strOutput);. That generates the form on the page, but it doesnt actuall process and send the form. The validation all works, but nothing else. So Im not sure if Im doing things wrong or what. On static pages you simply use: Code: [Select] <?php echo $strOutput; ?> If I do that only, the form doesnt show up. So ultimately I guess Im trying to figure out how one would write a 'return' into the code so that it works. I tried putting the return after the closing bracket, but Im not sure that is the correct way to do it. Does anyone have any ideas or input? I know MODx has the FormIt extension, but I really like ValidForm and would love to get it to work since, at least on static pages, it is easy to work with and set up. I need to redirect, back to the home page, after the form is submitted, but MODx handles that a little differently and I will have to figure that out after I get the form working. Thanks in advance for any help. Code: [Select] <?php //*** Include the library. require_once("libraries/ValidForm/class.validform.php"); //*** Create an instance of the form. $objForm = new ValidForm("contactForm", "Required fields are printed in bold."); //*** Add the Name field. $objForm->addField("name", "Your name", VFORM_STRING, array( "maxLength" => 255, "required" => TRUE ), array( "maxLength" => "Your input is too long. A maximum of %s characters is OK.", "required" => "This field is required.", "type" => "Enter only letters and spaces." ) ); //*** Add the Email field. $objForm->addField("email", "Email address", VFORM_EMAIL, array( "maxLength" => 255, "required" => TRUE ), array( "maxLength" => "Your input is too long. A maximum of %s characters is OK.", "required" => "This field is required.", "type" => "Use the format name@domain.com" ), array( "tip" => "name@domain.com" ) ); //*** Add the Remarks field. $objForm->addField("remarks", "Remarks", VFORM_TEXT, array( "maxLength" => 2000 ), array( "maxLength" => "Your input is too long. A maximum of %s characters is OK.", "type" => "Enter only characters, punctuation, numbers and spaces" ) ); //*** Set the general alert. $objForm->setMainAlert("One or more errors occurred. Check the marked fields and try again."); //*** Set the label of the submit button. $objForm->setSubmitLabel("Send"); //*** Default output. $strOutput = ""; //*** Check the form. if ($objForm->isSubmitted() && $objForm->isValid()) { //*** HTML body of the email. $strMessage = "<html><head><title></title></head><body>"; $strMessage .= $objForm->valuesAsHtml(); $strMessage .= "</body></html>"; //*** Mail headers. $strHeaders = "MIME-Version: 1.0\r\n"; $strHeaders .= "Content-type: text/html; charset=utf-8\r\n"; $strHeaders .= "From: Awesome website <form@awesomesite.com>\r\n"; //*** Send the email. mail("owner@awesomesite.com", "Contact form submitted", $strMessage, $strHeaders); //*** Set the output to a friendly thank you note. $strOutput = "Thank you for your interest. We will contact you as soon as possible."; } else { //*** The form has not been submitted or is not valid. $strOutput = $objForm->toHtml(); } ?> Hi guys, I'm having a bit of PHP problems trying to combine two bits of code which is definitely possible as it's simple if statements, but I'm a bit confused. Not sure if you guys are familiar, but there's a PHP Form Builder Class part of the Google Code Hosting Project. There's two forms I'm playing with one 'Google Spreadsheets' form which allows the data submitted via a form to be entered in a Google Spreadsheet, and one which sends the data to an email address. http://www.imavex.com/php-form-builder-class/examples/email.php http://www.imavex.com/php-form-builder-class/examples/google-spreadsheets.php I have these working separately, but ideally want I need is to be able to combine them both, per se, and allow the data submitted to go to both the spreadsheet and the email address defined. The code for the email is: Code: [Select] <?php error_reporting(E_ALL); session_start(); include("../class.form.php"); if(isset($_POST["cmd"]) && in_array($_POST["cmd"], array("submit_0"))) { $form = new form("email_" . substr($_POST["cmd"], -1)); if($form->validate()) { $result = $form->email("my_username", "my_password", array( "to" => "my_recipient(s)", "subject" => "my_subject", "from" => "my_from", "replyto" => "replyto", "cc" => "my_cc", "bcc" => "my_bcc", "preHTML" => "my_prehtml", "postHTML" => "my_posthtml", "css" => '<style type="text/css">...</style>', "cssFile" => "my_css.css or http://www.my_domain.com/my_css.css", "textonly" => "true/false" )); if($result) header("Location: email.php?errormsg_" . substr($_POST["cmd"], -1) . "=" . urlencode("Congratulations! The information you enter has been emailed from your Google Gmail account.")); else header("Location: email.php?errormsg_" . substr($_POST["cmd"], -1) . "=" . urlencode("Oops! The following error has occurred while sending information from your Google Gmail account. " . $form->getEmailError())); } else header("Location: email.php"); exit(); } elseif(!isset($_GET["cmd"]) && !isset($_POST["cmd"])) { $title = "Email w/PHPMailer + Google's Gmail Service"; include("../header.php"); ?> <p><b>Email w/Google's Gmail Service</b> - This project's email function provides the ability to email a form's submitted data using PHPMailer and Google's Gmail service. This function has four parameters as seen below.</p> <ul style="margin: 0;"> <li>Google Account Email Address - Email address (including domain) of your Google Gmail account.</li> <li>Google Account Password - Password of your Google Gmail account.</li> <li>Additional Parameters (optional) - This parameter allows you to set various email settings through an associative array of key/value pairs. Available settings are provided below. <ul style="margin: 0;"> <li>to - Sets the email's to address. If blank, this parameter will be set to the Google Gmail account email address used in the first parameter.</li> <li>subject - Sets the email's subject.</li> <li>from - Sets the email's from address. If blank, this parameter will be set to the Google Gmail account email address used in the first parameter.</li> <li>replyto - Sets the email's reply to address. If empty, the from address will be used.</li> <li>cc - Sets the email's CC address.</li> <li>bcc - Sets the email's BCC address.</li> <li>preHTML - Allows you to prepend html content above the form's submitted data.</li> <li>postHTML - Allows you to append html content below the form's submitted data.</li> <li>textonly - Sends text-only version of the form's submitted data. By default, the email function will send an email containing both an html and text version.</li> <li>css - Gives you the ability to style the html email as needed. This parameter should be passed as a string beginning with <style type="text/css"> and ending with </style></li> <li>cssFile - Gives you the ability to style the html email as needed by specifying a css include file.</li> </ul> </li> </ul> <p>Before getting started, you'll want to review the checklist of information provided below to ensure you have a good understanding on how this functionality works.</p> <ol style="margin: 0;"> <li>You'll need a Google Gmail account. If you don't have one, you can create one by clicking the "Create an account" link at <a href="http://mail.google.com">http://mail.google.com</a>.</li> <li>to, replyto, cc, and bcc can contain multiple email addresses - just separate them with commas.</li> <li>to, from, replyto, cc, bcc can contain email addresses formatted as either "my@email.com" or "My Email <my@email.com>"</li> <li>Within the email function, a call is made to another public function - getEmail - to get the email's html/text content. If you already have an existing system in place for sending email, you can use this function instead of the project's email function to build a string containing an html/text representation of the form's submitted data. By default, this function will return html, but you can pass true as the first and only parameter to return text.</li> </ol> <p>In the php source code of this example file, you'll see that the email function call currently contains demo authentication/email settings ("my_email", "my_password", etc). You'll want to replace these with your information. Another important thing to note is that the various email settings that can be applied through the email function's fourth parameter are optional. In the php source code of this example file, you'll find all of them listed for reference in the email function call. Feel free to include as many or few as needed.</p> <?php $form = new form("email_0"); $form->setAttributes(array( "map" => array(2, 2, 1, 3), "width" => 500 )); if(!empty($_GET["errormsg_0"])) $form->errorMsg = filter_var(stripslashes($_GET["errormsg_0"]), FILTER_SANITIZE_SPECIAL_CHARS); $form->addHidden("cmd", "submit_0"); $form->addTextbox("First Name:", "FName"); $form->addTextbox("Last Name:", "LName"); $form->addEmail("Email Address:", "Email"); $form->addTextbox("Phone Number:", "Phone"); $form->addTextbox("Address:", "Address"); $form->addTextbox("City:", "City"); $form->addState("State:", "State"); $form->addTextbox("Zip Code:", "Zip"); $form->addButton(); $form->render(); include("../footer.php"); } ?> And for the spreadsheet: Code: [Select] <?php error_reporting(E_ALL); session_start(); include("../class.form.php"); if(isset($_POST["cmd"]) && in_array($_POST["cmd"], array("submit_0"))) { $form = new form("googlespreadsheets_" . substr($_POST["cmd"], -1)); if($form->validate()) { if($form->sendToGoogleSpreadsheet("my_email", "my_password", "my_spreadsheet_title", "(optional) my_worksheet_title")) header("Location: google-spreadsheets.php?errormsg_" . substr($_POST["cmd"], -1) . "=" . urlencode("Congratulations! The information you enter has been sent your Google Docs spreadsheet.")); else header("Location: google-spreadsheets.php?errormsg_" . substr($_POST["cmd"], -1) . "=" . urlencode("Oops! The following error has occurred while sending information to your Google Docs spreadsheet. " . $form->getGoogleSpreadsheetError())); } else header("Location: google-spreadsheets.php"); exit(); } elseif(!isset($_GET["cmd"]) && !isset($_POST["cmd"])) { $title = "Google Spreadsheets"; include("../header.php"); ?> <p><b>Google Spreadsheets</b> - This project's sendToGoogleSpreadsheet function provides the ability to send a form's submitted data direclty to a Google Docs spreadsheet using the Google Spreadsheet API. This function has four parameters as seen below.</p> <ul style="margin: 0;"> <li>Google Account Email Address - Email address (including domain) of your Google account.</li> <li>Google Account Password - Password of your Google account.</li> <li>Google Docs Spreadsheet - The title of the spreadsheet where you'd like the form's submitted data to be sent.</li> <li>Worksheet (optional) - The title of the worksheet to be used within the specified spreadsheet. This parameter will default to the the spreadsheet's first worksheet.</li> </ul> <p>Before getting started, you'll want to review the checklist of information provided below to ensure you have a good understanding on how this functionality works.</p> <ol style="margin: 0;"> <li>You'll need a Google account. If you don't have one, you can create one by clicking the "Create an account now" link at <a href="http://docs.google.com">http://docs.google.com</a>.</li> <li>If the spreadsheet title you specify in the sendToGoogleSpreadsheet function does not exist, a new spreadsheet will be created for you with the appropriate title and column headers.</li> <li>If you're creating your spreadsheet manually through the Google Docs GUI, an important thing to keep in mind is that Google will treat the initial row of cells as column identifiers. These column identifiers must match an element's label used in your form ("First Name:", "Last Name:", etc), which enables the form's submitted data to be correctly placed within the appropriate column. If the spreadsheet you specify in the sendToGoogleSpreadsheet function exists but has no inital row of column headers, your form's data will not populated upon submission. Your spreadsheet does not need to contain a column for every element used in the form - data for those elements that are not included will just not be collected. Likewise, your spreadsheet can contain column identifiers that don't match an element's label used in the form - data for those columns will be left blank.</li> <li>Elements of type hidden, captcha, button, html, and htmlexternal will not be included in the information that is sent to your Google spreadsheet.</li> <li>The "ignoreGSSend" element attribute can be applied to form elements that you do not want to be send to your Google Docs spreadsheet. The hidden field "cmd" has this attribute set in the form below.</li> <li>If you're populating an existing spreadsheet in your Google Docs account, you can store the web server's date/time at the moment the form's data is submitted by adding "Timestamp" as a column header.</li> </ol> <p>In the php source code of this example file, you'll see that the sendToGoogleSpreadsheet function call currently contains demo authentication/spreadshet settings ("my_email", "my_password", etc). You'll want to replace these with your information.</p> <?php $form = new form("googlespreadsheets_0"); $form->setAttributes(array( "map" => array(2, 2, 1, 3), "width" => 500 )); if(!empty($_GET["errormsg_0"])) $form->errorMsg = filter_var(stripslashes($_GET["errormsg_0"]), FILTER_SANITIZE_SPECIAL_CHARS); $form->addHidden("cmd", "submit_0"); $form->addTextbox("First Name:", "FName"); $form->addTextbox("Last Name:", "LName"); $form->addEmail("Email Address:", "Email"); $form->addTextbox("Phone Number:", "Phone"); $form->addTextbox("Address:", "Address"); $form->addTextbox("City:", "City"); $form->addState("State:", "State"); $form->addTextbox("Zip Code:", "Zip"); $form->addButton(); $form->render(); include("../footer.php"); } ?> I have managed to speak to one of the admins, who can't help me further, but states: 'My recommendation would be to use both the $form->email() and $form->sendToGoogleSpreadsheet() methods after your form has been submitted. It's not a "one or the other" type of scenario.' Could you help me out and show me how this would be possible which in turn I can learn from? Thanks, and sorry for the long post but felt it was better as a code include rather than an attachment? Richard In attachment is the code I generated from Flex Builder: My issue is that the UTF8 (coding of the MySQL database) isn't correctly interpreted, the solution is to use : $stmt = mysqli_prepare($this->connection, "SET NAMES UTF8;"); But I don't know how to enter it in this syntax? It is I think the: $stmt = mysqli_prepare($this->connection, "SELECT * from $this->tablename"); that has to be modified, but how? Really searching a long time on the correct syntax, but without any result... Please help, thanks a lot Wimmerke Hello guys. By the end of the day, my client wants the daily report sent to his email account in .xls format. how can i attain this? I know the php mail() function but i dont know how will php create an excel file and email it to my client automatically. Where should i start? Thanks guys! hi, i looking for a design report like crystal report or active reports but for php the objective is creat a report using mysql data and save the template and load that report in a pdf file for print or save any one know something like that? i already use classes like class.ezpdf.php but i spend many hours creating complex reports, all is created using a text editor.. thanks for your help Hi Guys My site has a shout box, now and again people post inappropriate content and if a moderator is not online to mute them it doesnt look good for other users. I have written a snippet of code to report an offender. My goal is that if 3 different people report an offender the site auto mutes them. (manual mute function already exists for moderators) I setup a table that records the reporters name the offenders name the post id the message content and the time stamp. I have never been good at counting num rows etc and need some help in what direction to go in. My current code that inserts the reported content. Code: [Select] mysql_query("INSERT INTO `chicka_pets`.`records_sbreports` (`id`, `offender`, `reporter`, `post_id`, `post_content`, `timestamp`) VALUES ('', '$offender', '$username', '$id', '$sbmessage', '$timestamp')"); I am guessing that somewhere after that I need some sort of count numrows on the post id where reporter is NOT the same and then an if numrows >2 set offender to mute my problem is how to do the num rows bit where the reporters are unique? Any help is much appreciated Hello I am using SQL Server 2008 and Xampp server for PHP. I am trying to call SQL Server reports from PHP and I am using the code from https://ssrsphp.code...ussions/577518# I can call the URL which connects to the Reports server from PHP but when I try to click the dropdown and run the reports I get an error. Fatal error: Class 'PReportException' not found in E:\PHP_SRS\ssrsphp\Factory\SSRSTypeFactory.php on line 75 Can someone please tell me how to fix this error ? Thanks Hi guys, I want to generate reports and i want to use some fields of one table and other fields of another table. How can i use that? Ex. customer(customer_id, full_name,name_with_initials, address, contact_number,gender) transaction_table(tran_ID, account_number,account_type,transaction_type, amount, Date) If i want to use only customer_id, tran_ID, full_name and amount how can i use them to generate reports. I want them to be taken as fields of one table and use it.. Thanks, Heshan Hello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads 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'm trying to update every record where one field in a row is less than the other. The code gets each row i'm looking for and sets up the query right, I hope I combined the entire query into one string each query seperated by a ; so it's like UPDATE `table` SET field2= '1' WHERE field1= '1';UPDATE `table` SET field2= '1' WHERE field1= '2';UPDATE `table` SET field2= '1' WHERE field1= '3';UPDATE `table` SET field2= '1' WHERE field1= '4';UPDATE `table` SET field2= '1' WHERE field1= '5'; this executes properly if i run the query in phpMyAdmin, however when I run the query in PHP, it does nothing... Any advice? I was just wondering if it's possible to run a query on data that has been returned from a previous query? For example, if I do Code: [Select] $sql = 'My query'; $rs = mysql_query($sql, $mysql_conn); Is it then possible to run a second query on this data such as Code: [Select] $sql = 'My query'; $secondrs = mysql_query($sql, $rs, $mysql_conn); Thanks for any help Say I have this query: site.com?var=1 ..I have a form with 'var2' field which submits via get. Is there a way to produce: site.com?var=1&var2=formdata I was hoping there would be a quick way to affix, but can't find any info. Also, the query could sometimes be: site.com?var2=formdata&var=1 I would have to produce: site.com?var2=updatedformdata&var=1 Is my only option to further parse the query? What would be the correct way to close a mysql query? At current the second query below returns results from the 1st query AND the 2nd query The 3rd query returns results from the 1st, 2nd and 3rd query. etc etc. At the moment I get somthing returned along the lines of... QUERY 1 RESULTS Accommodation 1 Accommodation 2 Accommodation 3 QUERY 2 RESULTS Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 QUERY 3 RESULTS Takeaways 1 Takeaways 2 Takeaways 3 Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 Code: [Select] <!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" /> <?php include($_SERVER['DOCUMENT_ROOT'].'/include/db.php'); ?> <title>Untitled Document</title> <style type="text/css"> <!-- --> </style> <link href="a.css" rel="stylesheet" type="text/css" /> </head><body> <div id="listhold"> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Placestostay.html">Places To Stay</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Accommodation' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingout.html">Eating Out</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Restaurant' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingin.html">Eating In</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Takeaways' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------SKILLED TRADES BELOW---------------------------------------------------> <div class="list"><a href="Skilledtrades.html">Skilled Trades</a><br/> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Skilled Trades' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> here's the code: Code: [Select] $companyName = 'big company'; $address1 = 'big bay #8'; $address2 = 'some big warehouse'; $city = 'big city'; $province = 'AB'; $postalCode = 'T1T0N0'; $phone = '0123456789'; $email2 = 'bigKahuna@bigKahuna.edu'; $query = "INSERT INTO clients ( companyName, address1, address2, city, province, postalCode, phone, email) VALUES ( ". $companyName.",".$address1.",".$address2.",".$city.",".$postalCode.",".$phone.",".$email2.")"; $result = mysql_query($query, $connexion); if ($result) { // Success! echo "Fabulous! check the DB, we did it! :D<br>"; ?> <pre> <?php print_r($result); ?> </pre> <?php } else { // Fail! echo"CRAAAAAPP! something went wrong. FIX IT! :P<br>"; echo mysql_error(); } if (isset($connexion)) { mysql_close($connexion); } i copied it over from an old *working* file to illustrate how a simple INSERT works. this is the error i get: 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 'company,big bay #8,some big warehouse,big city,T1T0N0,0123456789,bigKahuna@bigKa' at line 4 looks completely valid to me. all the database table elements are set to VARCHAR(80), so it can't be a space/type issue... halp! WR! 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? Good Day Guys
I have a bit of a urgent problem.
Here is my Query:
$query = "SELECT distinct Img.propertyId as PropertyId, Title, ImageUrl, Location, Bedrooms, Bathrooms, Parking, Price FROM PROPERTIES as Prop LEFT JOIN IMAGES as Img ON Img.PropertyId = Prop.PropertyId WHERE 1=1 AND Price >=1000 AND Price <=5000 "; I am trying to create a query which reads and uses a previous query which could go on for upto four queries. For example: Query: $carcolour(red), Query: $carmodel(ford), Query: $enginesize(1600), Query: $carlocation(New York) This displays all red cars, which are Ford, which 1600CC, which are located in New York. or Query: $enginesize(1600), Query: $carcolour(red), Query: $carmodel(ford), Query: $carlocation(New York) This displays all 1600CC cars, which red car, which are Ford, which are located in New York. (Same result as above) I have found this guide but Im not sure it what I am looking for. I have also come across the Join function. However this seems to be based on joining two seperate queries. http://www.suite101.com/content/how-tor-run-multiple-mysql-queries-with-php-a105672 Can anyone advise on the best way to create a set of queries which reads and uses the results of the previous query? perId
propId
firstName
lastName
1
1
Fred
Bloggs
2
2
Arthur
Brown
3
1
Mary
Bloggs
4
4
Nigel
Wilson
How would you write an SQL query to list the postcodes and the names of the occupants whose last name begins with a “B in the table above
|