PHP - Query Code Needs Some Tweaking...
I'm putting some code that works with one database into a new website. Problem is the 2nd database has a bit of a different structure than the 1st so I need to make some changes.
In the 1st database, I'm calling 2 different values that are contained in 1 row. In the 2nd database, I'm trying to call 2 values, but they are in different rows so I need to change my SELECT statement. This is the code that works in database 1: Code: [Select] $result = mysql_query(" SELECT S.game_id, TH.team_name AS HomeTeam, TA.team_name AS AwayTeam FROM schedule AS S JOIN teams AS TH ON S.team = TH.team_id JOIN teams AS TA ON S.team = TA.team_id WHERE S.week_id = '$weekID' ORDER BY S.game_id;"); while ($row = mysql_fetch_array($result)) { printf('<input type="text" size="4" name="spread[%d][%d][A]">', $weekID, $row['game_id']); printf(" %s vs. %s ", $row['AwayTeam'], $row['HomeTeam']); printf('<input type="text" size="4" name="spread[%d][%d][H]">', $weekID, $row['game_id']); } The 2nd database has one field to hold the team name and another field (place_id) to hold a single letter (H or A) to signify whether a team is Home or Away. (the 1st database has "A_team" and "H_team" fields in the same row.) They both use the tables "teams" and "schedule". Can I alter this code to look at 2 rows (place_id="H" and place_id="A") for the values without having to create 2 queries? Thanks. Similar TutorialsI have finally worked out how to get a football league table query up and running (mainly by stealing code from elsewhere and adapting it to work the way I want it to!) but need to try to tweak it for a couple of other pages. The test page with it on is at http://www.margate-fc.com/content/test/table.php The query is $i = 1; $ht = "g.home_team = t.team_id"; $at = "g.away_team = t.team_id"; $hw = "g.home_goals > g.away_goals"; $aw = "g.home_goals < g.away_goals"; $d = "g.home_goals = g.away_goals"; $hg ="g.home_goals"; $ag ="g.away_goals"; $table = mysql_query("SELECT t.team_name as Tm, @rownum := @rownum+1 AS rank , (sum(CASE WHEN (".$ht." AND ".$hw.")OR(".$at." AND ".$aw.") THEN 3 ELSE 0 END) + sum(CASE WHEN (".$ht." OR ".$at.") AND ".$d." THEN 1 ELSE 0 END)) AS P , (sum(CASE WHEN (".$ht." AND ".$hw.") THEN 3 ELSE 0 END) + sum(CASE WHEN (".$ht.") AND ".$d." THEN 1 ELSE 0 END)) AS HP , (sum(CASE WHEN (".$at." AND ".$aw.") THEN 3 ELSE 0 END) + sum(CASE WHEN (".$at.") AND ".$d." THEN 1 ELSE 0 END)) AS AP , count(CASE WHEN (".$ht." OR ".$at.") THEN 1 ELSE 0 END) as GP , sum(CASE WHEN (".$ht." ) THEN 1 ELSE 0 END) as HGP , sum(CASE WHEN ".$at." THEN 1 ELSE 0 END) as AGP , sum(CASE WHEN (".$ht." AND ".$hw.") OR (".$at." AND ".$aw.") THEN 1 ELSE 0 END) AS W , sum(CASE WHEN (".$ht." AND ".$hw.") THEN 1 ELSE 0 END) AS HW , sum(CASE WHEN (".$at." AND ".$aw.") THEN 1 ELSE 0 END) AS AW , sum(CASE WHEN (".$ht." AND ".$d.") OR (".$at." AND ".$d.") THEN 1 ELSE 0 END) AS D , sum(CASE WHEN (".$ht." AND ".$d.") THEN 1 ELSE 0 END) AS HD , sum(CASE WHEN (".$at." AND ".$d.") THEN 1 ELSE 0 END) AS AD , sum(CASE WHEN (".$ht." AND ".$aw.") OR (".$at." AND ".$hw.") THEN 1 ELSE 0 END) AS L , sum(CASE WHEN (".$ht." AND ".$aw.") THEN 1 ELSE 0 END) AS HL , sum(CASE WHEN (".$at." AND ".$hw.") THEN 1 ELSE 0 END) AS AL , SUM(CASE WHEN (".$ht.") THEN ".$hg." WHEN (".$at.") THEN ".$ag." END) as GF , SUM(CASE WHEN (".$ht.") THEN ".$hg." END) as HGF , SUM(CASE WHEN (".$at.") THEN ".$ag." END) as AGF , SUM(CASE WHEN (".$ht.") THEN ".$ag." WHEN (".$at.") THEN ".$hg." END) as GA , SUM(CASE WHEN (".$ht.") THEN ".$ag." END) as HGA , SUM(CASE WHEN (".$at.") THEN ".$hg." END) as AGA , (SUM(CASE WHEN (".$ht.") THEN ".$hg." WHEN (".$at.") THEN ".$ag." END) - SUM(CASE WHEN (".$ht.") THEN ".$ag." WHEN (".$at.") THEN ".$hg." END)) as GD , (SUM(CASE WHEN (".$ht.") THEN ".$hg." END) - SUM(CASE WHEN (".$ht.") THEN ".$ag." END)) as HGD , (SUM(CASE WHEN (".$at.") THEN ".$ag." END) - SUM(CASE WHEN (".$at.") THEN ".$hg." END)) as AGD from teams t left join all_games g on t.team_id in (g.home_team,g.away_team) WHERE comp = '1' AND home_goals IS NOT NULL AND date BETWEEN '2010-07-01' AND '2011-06-31' GROUP BY t.team_id ORDER BY P desc, GD desc, GF desc and the html (although some of the css still is not done and some code still needs tidying) is Code: [Select] <table width="" border="0" cellpadding="0" cellspacing="0" BORDER=1 RULES=ROWS FRAME=BOX> <tr> <td></td><td></td> <td colspan="9" align="center" bgcolor="#00FF99">ALL</td> <td colspan="9" align="center" >Home</td> <td colspan="9" align="center">Away</td> </tr> <tr> <td class="hdcell" >POS</td> <td class="hdcell" >Team</td> <td width="30" class="hdcell">P</td> <td width="30" class="hdcell">W</td> <td width="30" class="hdcell">D</td> <td width="30" class="hdcell">L</td> <td width="30" class="hdcell">F</td> <td width="30" class="hdcell">A</td> <td width="30" class="hdcell">GD</td> <td width="30" class="hdcell">Pts</td> <td width="30" class="hdcell"></td> <td></td> <td width="30" class="hdcell">P</td> <td width="30" class="hdcell">W</td> <td width="30" class="hdcell">D</td> <td width="30" class="hdcell">L</td> <td width="30" class="hdcell">F</td> <td width="30" class="hdcell">A</td> <td width="30" class="hdcell">GD</td> <td width="30" class="hdcell">Pts</td> <td></td> <td width="30" class="hdcell">P</td> <td width="30" class="hdcell">W</td> <td width="30" class="hdcell">D</td> <td width="30" class="hdcell">L</td> <td width="30" class="hdcell">F</td> <td width="30" class="hdcell">A</td> <td width="30" class="hdcell">GD</td> <td width="30" class="hdcell">Pts</td> </tr> <?php while ($row_table = mysql_fetch_assoc($table)){ echo '<tr> <td style="text-align:left" width="30">'.$i.'</td>'; echo '<td style="text-align:left">'.$row_table['Tm'].'</td> <td style="text-align:left">'.$row_table['GP'].'</td> <td style="text-align:left">'.$row_table['W'].'</td> <td style="text-align:left"> '.$row_table['D'].'</td> <td style="text-align:left"> '.$row_table['L']. '</td> <td style="text-align:left"> '.$row_table['GF']. '</td> <td style="text-align:left"> '.$row_table['GA']. '</td> <td style="text-align:left"> '.$row_table['GD']. '</td> <td style="text-align:left"> '.$row_table['P']. '</td> <td style="text-align:left"></td> <td style="text-align:left"></td> <td style="text-align:left">'.$row_table['HGP'].'</td> <td style="text-align:left">'.$row_table['HW'].'</td> <td style="text-align:left">'.$row_table['HD'].'</td> <td style="text-align:left"> '.$row_table['HL']. '</td> <td style="text-align:left"> '.$row_table['HGF']. '</td> <td style="text-align:left"> '.$row_table['HGA']. '</td> <td style="text-align:left"> '.$row_table['HGD']. '</td> <td style="text-align:left"> '.$row_table['HP']. '</td> <td style="text-align:left"></td> <td style="text-align:left">'.$row_table['AGP'].'</td> <td style="text-align:left">'.$row_table['AW'].'</td> <td style="text-align:left">'.$row_table['AD'].'</td> <td style="text-align:left"> '.$row_table['AL']. '</td> <td style="text-align:left"> '.$row_table['AGF']. '</td> <td style="text-align:left"> '.$row_table['AGA']. '</td> <td style="text-align:left"> '.$row_table['AGD']. '</td> <td style="text-align:left"> '.$row_table['AP']. '</td> </tr>'; $i++; } ?> </table> As I said, this works fine in the test page but there are two other things that I am looking to do with it and one way I hope to streamline the code. Firstly the code bit..... There is a bit of replication that I was hoping to eliminate by using the sum function but from what I can see this cannot be done with Alias's. I was hoping to change the code , sum(CASE WHEN (".$ht." AND ".$hw.") OR (".$at." AND ".$aw.") THEN 1 ELSE 0 END) AS W , sum(CASE WHEN (".$ht." AND ".$hw.") THEN 1 ELSE 0 END) AS HW , sum(CASE WHEN (".$at." AND ".$aw.") THEN 1 ELSE 0 END) AS AW to , sum(HW + PW) AS W , sum(CASE WHEN (".$ht." AND ".$hw.") THEN 1 ELSE 0 END) AS HW , sum(CASE WHEN (".$at." AND ".$aw.") THEN 1 ELSE 0 END) AS AW but that just causes no records to be shown. Is there a way around this or is there no way to aggregate alias's? Secondly, the other pages. There are 2 other pages that I want to use similar data on and I think what I want to do is quite simple. On the front page of the site I want a stripped down version of the table which shows just five records, that of my team, Margate, and the two positions above and two below. At the moment Margate are in 19th position so I would want it to show rows 17,18,19,20,21. If Margate were 10th I would want it to show 8,9,10,11,12. I would imagine that there is a way of finding which position Margate is in then setting the OFFSET to that -2 but after extensive Googling (I did spot it in exactly the context I need some time back when I did not need it!) I cannot find anything as I basically do not know what I need to ask for! The final thing is that each team has its own page and on that page I want to show their position in the League in a friendly style, such as 19th as opposed to 19. I would imagine that I would need to pull the whole league table in as opposed to using a query that matches the team otherwise it would only have one result and each team would show as being 1st. I would only want to show the position of the relevant team but obviously the whole query would need to be run to get that position. How would I then find the relative teams position? I think that the ideal thing would be to use a VIEW but am working with a MySQL 4 database. Any help or advice will, as always, be appreciated. Thanks in advance Steve 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 Is there a way that I can tweak the following code so that the root nodes have different names? At the moment the xml file is creating a root node for each booking called booking so when I take the xml into flash it is calling it badly formed xml due to the repitition of <booking></booking> //sql_query $table_id = 'booking'; $query = "SELECT * FROM $table_id WHERE (booking.bookingDate = curDate()) AND roomID = 1 ORDER BY startTime"; $room1 = mysql_query($query); //create a new DOM document $doc = new DOMDocument('1.0'); //create root element $root = $doc->createElement('root'); $root = $doc->appendChild($root); //process one row at at time while($row = mysql_fetch_assoc($room1)){ //add node for each row $occ = $doc->createElement($table_id); $occ = $doc->appendChild($occ); //add achild for each field foreach ($row as $fieldname => $fieldvalue){ $child = $doc->createElement($fieldname); $child = $occ->appendChild($child); $value = $doc->createTextNode($fieldvalue); $value = $child->appendChild($value); } } $xml_string = $doc->saveXML(); echo $xml_string; mysql_free_result($room1); ?> Help wanted with tweaking PHP script
Hey everyone, im having problems querying the results from the database using this query.... $get_points = mysql_query("SELECT * FROM points WHERE ACOS( (SIN(PI() * '41.896301269531' / '180') * SIN(PI() * latitude / '180')) + (COS(PI() * '41.896301269531' /'180') * COS(PI() * latitude / '180') * COS(PI() * longitude / '180' - PI() * '-88.744201660156' / '180')) )* '180' / PI() * '60' * '1.1515' <= '80'") or die(mysql_error()); Basically what it does it checks the for location with in 80 miles of the lat and long coordinates. The problem is no result are showing up. I know there are locations because i tested this as an sql code in my database and it ran perfectly, but i can't get it to work using php.. I get no errors, nothing. can anyone help me out? Hello!
I'm hoping this makes sense.
Basically I have this code:
What it does
1) Looks at the XML
2) Looks for the PIN number in the URL, then finds it in the XML
3) Returns values for the PIN number (which is a profile) allowing me to do echo statements like name, tools, description, etc.
<?php if (!empty($_GET['pin'])) { $feedURL = 'http://www.inveroak.co.uk/readerimages/livepanel/91255.xml'; $showOpsWithNoPics = false; try { $xml = simplexml_load_file($feedURL . '?' . time()); $readers = $xml->xpath('/ReaderDetails/Reader[Pin="' . $_GET['pin'] . '"]'); foreach ($readers as $reader) { if ($reader->Picture == 'None' && $showOpsWithNoPics == false) { $picture = ''; } elseif ($reader->Picture == 'None' && $showOpsWithNoPics == true) { $picture = 'images/defaultpic.jpg'; } else { $picture = $reader->Picture; } if ($picture != '') { $name = $reader->Name; $pin = $reader->Pin; $status = $reader->Status; $description = $reader->Description; $arr_skills = ''; $arr_subjects = ''; foreach ($reader->Categories->Category as $Category) { foreach ($Category->Skill as $Skill) { switch ($Category['name']) { case 'Skills': $arr_skills .= "<li>$Skill</li>"; break; case 'Subjects': $arr_subjects .= "<li>$Skill</li>"; break; } } } $arr_shift = ''; $hourWidth = 20; $PreviousDate = ""; foreach ($reader->Rota->Shift as $Shift) { $Date = $Shift['Date']; $Day = date("l", strtotime($Date)); $Start = $Shift['Start']; $Stop = $Shift['Stop']; if($Stop == '23:59:59' || $Stop == '00:00:00' ){$Stop = '24:00:00';} $Left = date("H",strtotime($Date.' '.$Start)) * $hourWidth; $Width = (round(abs(strtotime($Date.' '.$Stop) - strtotime($Date.' '.$Start)) / 60,2)/60)*$hourWidth; $compare = strcmp ($PreviousDate, $Date); if ($compare != 0) { if ($PreviousDate != '') { //this is not the first loop so close off the previous dayrow and hours divs $arr_shift.= '</div></div>'; } //create a new day row $arr_shift .= '<div class="dayrow">'; $arr_shift .= '<div class="day">'.$Day.'</div>'; $arr_shift .= '<div class="hours">'; } //add the shift object $arr_shift .= '<div class="shift" title="'. substr($Start,0,5).'-'.substr($Stop,0,5) .'" style="left:'.$Left.'px; width:'.$Width.'px; opacity: 1;"></div>'; //set previouse date to the current shift's date so that we can check if we need to create a new day row next loop $PreviousDate = $Date; } //now we have finshed looping the shifts, either close the last div or display a message to show //we have no schedule for the op if ($Date != "") { $arr_shift.= '</div></div>'; } else { $arr_shift.= 'We are sorry but they have not scheduled their hours this week. Email for further details.'; } } } } catch (Exception $e) { echo 'cannot display operator profile'; } } ?>What I am want to achieve 1) Looks at the XML 2) Looks for a set PIN number in the CODE, then finds it in the XML 3) Returns values for the PIN number (which is a profile). I am just wanting to know what the other forms of this type of conditonal would be, the type of if statement is as follows: if ($_POST) {print_r($_POST);} Just seen it a few times now, I know this means if $_POST exists. use the print_r() function to display the entire post array suber global variable. But what are the other combinations other than just if true? Like how are they used like this, like if I wanted to see if a random variable is not identical to another etc. Any helps appreciated, Jez. Hi, we are trying to make a marketing wheel. This means we got a database with lots of persons in it each with a individual email adres. The simel example of how the basic database looks is seen in the picture below. This table is called "Clicks" As you might notice the field "Aan" is either a 0 or a 1. This is how it works, when someone fills in a form on the website asking for more information the form with all the personal information of this person is send to a random email adres found in this table. When this happens the field "Aan" changes from 0 to 1 this way we can make sure that the same person does not get a email again until everyone else has been used 1 time. So in other words until that the field "Aan" is value 1 for every person in the table. As you might have guessed this is sadly enough not working ... this is our code : Code: [Select] include_once('connection.php'); $data = array(); $i = 0; $result1 = mysql_query("SELECT * FROM `Clicks` WHERE Aan = 0"); while ($list1 = mysql_fetch_array($result1,MYSQL_ASSOC)) { if (empty($list1) ){ mysql_query("UPDATE `Clicks` SET `Aan`= 0 WHERE `Aan` = 1"); } $result = mysql_query("SELECT * FROM `Clicks` WHERE Aan = 0 ORDER BY RAND() LIMIT 1"); while ($list = mysql_fetch_array($result,MYSQL_ASSOC)) { foreach ($list as $key => $value) { // Met htmlentities() voorkom je dat html wordt uitgevoert. $value = htmlentities($value); $data[$i][$keyl] = $value; } $i++; } } mysql_free_result($result); $data = array_reverse($data); // Zet de nieuwste berichten bovenaan // in plaats van onderaan. $cnt = count($data); for($i = 0; $i < $cnt; ++$i) { $bericht = $data[$i]; echo(nl2br($bericht['bericht'])); // Met nl2br() worden alle enters in het // bericht omgezet naar <br/>. echo('</td></tr></table>'); $naarwie= $bericht['Email']; }mysql_query("UPDATE `Clicks` SET `Aan`= 1 WHERE `Email` = $naarwie"); mysql_close($Verbinding); // Sluit de verbinding. // We hebben hem nu niet meer nodig. So this code in short explained would be. It checks if all the "Aan" fields are on 0 if the list is empty so it means they are all on 1 he will reset all the fields of every user to 0. and then he will take a random person out and send the email to that person. And after the mail is send will change that person his value on "Aan" to value 1. Now if the list is not empty, that means there are still persons with value 0 in the list. Then he will take a random user out of all the persons who have "Aan" with value 0 send the mail to that user and change his "Aan" value to 1. This process will be repeated every time someone asks for information until all values of all users are on 1. And then again he will change them to 0 for everyone. I hope its clear what we are looking for. And I hope someone can help us out. We are clueless... I had a programmer who was doing a job for me look over one of my pages and added this security to my POST submit button: Code: [Select] ##### secure ##### if(!empty($_POST['user_url']) & preg_match('/(order.*?by|union.*?select|select.*?from|update.*?set|"|\'|\/*)/', $_POST['user_url'])) exit; if(!empty($_POST['user_url']) & !preg_match('/https?:\/\/[\w\d:#@%\/;$()~\\_?+-=.&]*/', $_POST['user_url'])) exit; ################# However now it doesnt matter what i type into the text box it always Exits the script... can anyone see whats happening here? PS. the purpose the of the text box is to insert URLs into my database... so it would need to allow that format. I spent the last hour or so typing this code up, and for some reason I am getting a query error. I have reviewed & revised the code up and down for the past half hour and can't seem to figure out the problem. Can someone look after this for me and tell me what I could be doing wrong? Yes, I know my code is a bit sloppy and may use bad practice techniques, but it works for me. Its a survey that I coded so I could collect data and place it on CPA ad listings. So I need this so work at some point soon. My code: <?php $user = $_POST['user']; $email = $_POST['email']; $password = $_POST['pass']; $paypal = $_POST['paypal']; $q1 = $_POST['q1[favsite]']; $q2 = $_POST['q2[isp]']; $q21 = $_POST['q2.1[bill]']; $email_services = $_POST['email_services']; $ebay = $_POST['ebay']; $amazon = $_POST['amazon']; $q6 = $_POST['q6[purchase]']; $q7 = $_POST['q7[social]']; $q8 = $_POST['q8[bookmarks]']; $q9 = $_POST['q9[search]']; $q10 = $_POST['q10[homepage]']; $q11 = $_POST['q11[5topsites]']; $q12 = $_POST['q12[state]']; if ($_POST['fin'] == "complete") { $dbc = mysqli_connect('localhost', 'root', 'password', 'database') or die('Could not connect'); $query = "INSERT INTO user_data (id, user, email, password, paypal, q1[favsite], q2[isp], q21[bill], email_services, ebay, amazon, q6[purchase], q7[social], q8[bookmarks], q9[search], q10[homepage], q11[5topsites], q12[state]) VALUES ('$user', '$email', '$password', '$paypal', '$q1', '$q2', '$q21', '$email_services', '$ebay', '$amazon', '$q6', '$q7', '$q8', '$q9', '$q10', '$q11', '$q12')"; mysqli_query($dbc,$query) or die('Error querying database'); include_once("../phpmailer/class.phpmailer.php"); $mail = new PHPMailer; $mail->ClearAddresses(); $mail->AddAddress('', ''); $mail->From = ''; $mail->FromName = ''; $mail->Subject = 'Thanks for finishing the survey!'; $mail->Body = "Hello, $user. This is a reminder that you have finished the survey and your credit is currently being processed. Please login to your account at ../../ to view the status of your credit & cash out. "; if ($mail->Send()) { echo "<center>Mail Sent.</center>"; } else { echo $mail->ErrorInfo; } echo "<center><h2>Thanks for completing the survey! Please <a href='login.php'>login</a> to your account to view the status of your credit & cash out.</h2></center>"; } ?> It has nothing to do with PHPMailer, I of course edited the variables just now so all my info wouldnt be public, but everything is fine untill you press submit & I get the or die() error message "Error querying database". What the hell did I do wrong? Is it possible that I cant name variables in the format I used with most of them ($var1 = $_POST['var[desc]']; ? 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? 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? 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 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! 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> 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? |