PHP - Having A For Loop Inside A Mysql Select Statement
Is it possible to have a loop inside a mysql select statement? If yes, can someone please give me an idea.
Similar TutorialsAfter it goes through the while loop its supposed to take the ID of the first one in the loop and find out its awardType and then with the awardType variable go through the the if statement. After it displays it the code that fits the awardType variable then it gets the second item in the while loop and then with the ID of the second item takes it back to get the awardType and then goes back through the if statement again. I'm not sure what I'm doing wrong. As of right now all its doing is displaying its awardName and a blank dropdown. Code: [Select] <?php session_start(); // Access the existing session // Include the database page require ('../../inc/dbconfig.php');l $userID = $_SESSION['userID']; $statusQuery = " SELECT * FROM statuses"; $statusResult = mysqli_query ( $dbc, $statusQuery ); // Run The Query $awardQuery = " SELECT awards.ID, awards.awardName, awards.awardType FROM awards"; $awardResult = mysqli_query ( $dbc, $awardQuery ); // Run The Query $row = mysqli_fetch_array ( $awardResult, MYSQL_ASSOC ); $awardType = $row[ 'awardType' ]; $charactersQuery = " SELECT characters.ID, characters.characterName FROM characters ORDER BY characters.characterName"; $charactersResult = mysqli_query ( $dbc, $charactersQuery ); // Run The Query $matchQuery = " SELECT eventSegments.ID, eventSegments.segmentTitle FROM eventSegments INNER JOIN events ON eventSegments.eventID = events.ID WHERE DATE_FORMAT(events.bookingDate,'%Y') = DATE_FORMAT(curdate(),'%Y')"; $matchResult = mysqli_query ( $dbc, $matchQuery ); // Run The Query ?> Code: [Select] <fieldset> <legend>Nominees</legend> <?php mysqli_data_seek( $awardResult, 0 ); while ( $row = mysqli_fetch_array ( $awardResult, MYSQL_ASSOC ) ) { ?> <?php if ($awardType == 'Singular') { ?> <div class="field required"> <label for="charactersDrop"><?php echo $row['awardName']; ?></label> <select class="dropdown" name="charactersDrop" id="charactersDrop" title="Characters Drop"> <option value="">- Select -</option> <?php while ( $row = mysqli_fetch_array ( $charactersResult, MYSQL_ASSOC ) ) { print "<option value=\"".$row['ID']."\">".$row['characterName']."</option>\r"; } ?> </select> <input type="button" value="Add Character" class="" onclick="HandlerCharacters()"/> <ul id="characterList"> </ul> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <? } else { ?> <div class="field required"> <label for="events"><?php echo $row['awardName']; ?></label> <select class="dropdown" name="events" id="events" title="Events for <?php echo date("Y") ?>"> <option value="">- Select -</option> <?php while ( $row = mysqli_fetch_array ( $matchResult, MYSQL_ASSOC ) ) { print "<option value=\"".$row['ID']."\">".$row['segmentTitle']."</option>\r"; } ?> </select> <input type="button" value="Add Match" class="" onclick="AddMatch()"/> <ul id="matchList"> </ul> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <?php } ?> <?php } ?> Hi Guys I don't know if this is possible but can someone point me in the right direction. I have a php function which takes two inputs and returns an output. for simplicity's sake let's say it's an addition function. What I want to do is use a mysql select statement to show all the rows from a database where field1 and field2 equal '3'. Here's the sort of thing I mean. function addNumbers($one,$two) { return $one + $two; } mysql_query("SELECT * FROM table WHERE 'addNumbers(field1,field2)' = '3'"); What I actually want to do is a lot more complex than this but I am trying to understand how to make the syntax work in simple terms first. Can anybody help? Many Thanks Dan Hi,
Does anyone have a clue how I might solve this little issue:
I have a MySQL query, for example:
<?php // Make a MySQL Connection $query = "SELECT * FROM staff"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ if($row['clock'] < time()) { echo "<b>"$row['name']. " - ". $row['age']"</b>"; echo "<br />"; } else { echo $row['name']. " - ". $row['age']; echo "<br />"; } } ?>Taking data from the following table setup: name - age - clock Timmy Mellowman - 23 - 09:00:00 Sandy Smith - 21 - 12:00:00 Bobby Wallace - 15 - 14:00:00 What im trying to achieve is compare the current time to the time in the clock column and depending if it's earlier or later, change the styling of the results. The above code does appear to work somewhat however it seems to change the styling of all results in one go, rather than individually when it passes the time in the cell, which is what im looking for. Thanks I am really just a beginner in PHP but I've got a task to create a simple hotel booking system by using PHP and MySQL. It works in several steps, described in separate .php files. All of them seem to work fine, except the last one. In this last file I want to add all the data into a MySQL database table. I would like to do this by creating a record for each date, a guest is spending in a hotel (so that when booking, another loop checks whether the room is not occupied yet for that date). I decided to use a for-loop for that, but it doesn't seem to be working (the records just don't get inserted into the table). I checked all the variables by echo-ing them and they are all right. I also tried the query without the loop and it works as well. So I guess there is some other problem. This particular .php file looks as follow: <?php session_start(); include('db_config.php'); $name=($_POST['name']); $telephone=addslashes($_POST['telephone']); $email=addslashes($_POST['email']); $code=md5($email.time()); $checkout_date=$_SESSION['checkout']; $checkin_unix=$_SESSION['checkin_unix']; $checkout_unix=$_SESSION['checkout_unix']; $roomtype=$_SESSION['roomtype']; $checkin_date=$_SESSION['checkin']; for ($stay_date=$checkin_unix; ; $stay_date=$stay_date+24*60*60) { if ($stay_date=$checkout_unix){ break; } mysql_query("INSERT INTO reservations VALUES( '', '$roomtype', 'pending', 'date ('d/m/Y', $stay_date)', '$stay_date', '$checkout_date', '$name', '$telephone', '$email', '$code' )"); } ?> I would appreciate any kind of help, any idea. I have a table called "playlists", and a table called "musics". In the musics table, there is a column playlist_id which references the playlist that each music is contained.
I'm using api calls to display information on the site with JavaScript, so I need to return a JSON.
I need the json with the following structu
[
Playlists: [
{
Name: "etc",
musics: [
{
name: "teste.mp3" }, { name: "test2.mp3" } ] }, ... ] ] And this is my code: $query = $con->prepare("SELECT * FROM playlists WHERE user_id = :id"); When I run 'select 1700-price as blah from goldclose as t2 order by dayid desc limit 1' by itself in mysql I get a numerical result: one row, one column. In my php script, the 1700 is actually a variable. so here it is $changequery = sprintf("select $goldprice-price as change from goldclose order by dayid desc limit 1"); $change = mysql_query(changequery); while ($row = mysql_fetch_array($change)) { printf("$row[0]"); } mysql_free_result($changeresult); I get the following error, Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>/root/fuzzy/htmlmain4.php on line 99 Warning: mysql_free_result(): supplied argument is not a valid MySQL result resource in <b>/root/fuzzy/htmlmain4.php on line 103 Not sure why? All i want is to get the result of that select statement into a variable such as $change The Script:
$desired_width = 110; if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; $tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())"; $tqr = mysqli_query($dbc, $tqs); // Select the ID numbers of the last inserted images and store them inside an array. // Use the implode() function on the array to have a string of the ID numbers separated by commas. // Store the ID numbers in the "image_file_id" column of the "thread" table. $tqs = "SELECT `id` FROM `images` WHERE `image_file` IN ('$new_image_name')"; $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc)); $fetch_array = array(); $row = mysqli_fetch_array($tqr); $fetch_array[] = $row['id']; /* * This prints e.g.: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 ) */ print_r($fetch_array); // Goes over to create the thumbnail images. $src = $target_path; $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/" . $new_image_name; make_thumb($src, $dest, $desired_width); } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } }Hey, sorry that I am posting this darn image upload script again, I have this almost finished and I am not looking to ask more questions when it comes to this script specifically. With the script above I have that part where the script should store the ID numbers (the auto_increment column of the table) of the image files inside of one array and then the "implode()" function would get used on the array and then the ID numbers would get inserted into the "image_file_id" column of the "thread" table. As you can see at the above part the script prints the following: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 )And I am looking to insert into the column of the table the following: 542, 543, 544I thought of re-writing the whole image upload script since this happens inside the for loop, though I thought maybe I could be having this done with the script as it is right now. Any suggestions on how to do this? I'm having issues with the following: Code: [Select] <?php session_start(); $_SESSION['username']=$_POST['username']; $_SESSION['password']=$_POST['password']; if($_SESSION['username']=="username" && $_SESSION['password']=="password"){ if($_GET['product']=="add"){ $content.=' <p><label>Product Name:</label> <input type="text" name="product_name" size="30" /> <label>Product Price:</label> <input type="text" name="product_price" size="5" /> </p> <p><label>Product Category:</label> <input type="text" name="product_category" size="30" /></p> <p><label>Product Link:</label> <input type="text" name="product_link" size="30" /></p> <p><label>Product Image:</label> <input type="text" name="product_image" size="30" /></p> <p><label>Product Tag:</label> <input type="text" name="product_tag" size="30" /></p> <p><label>Product Keywords:</label> <input type="text" name="keyword" size="30" /></p> <p><label>Product Features:</label><br /> <textarea name="product_features" rows="10" cols="60"></textarea> </p> <p><label>Product Pros:</label><br /> <textarea name="product_pros" rows="5" cols="30"></textarea> </p> <p><label>Product Cons:</label><br /> <textarea name="product_cons" rows="5" cols="30"></textarea> </p> <p><label>Product Description:</label><br /> <textarea name="product_description" rows="10" cols="60"></textarea> </p> <p><label>Product Notes:</label><br /> <textarea name="product_notes" rows="5" cols="30"></textarea> </p> '; $logout='<div><a href="./acp_admincp.php?log-out">Log-Out</a></div>'; } elseif($_GET['product']=="view"){ } else{ $content.=' <a href="./admincp.php?product=add">Add New Product</a> <br /> <a href="./admincp.php?product=view">View Products</a> '; } } elseif(isset($_GET['log-out'])){ session_start(); session_unset(); session_destroy(); header("Location: ./admincp.php"); } else{ $content=' <form action="./admincp.php" method="post"> <p><label>Username:</label> <input type="text" name="username" size="30" />'; $content.='</p> <p><label>Password:</label> <input type="password" name="password" /></p>'; $content.='<p><input type="submit" value="Submit" name="Submit" /></p> </form>'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <base href="http://ghosthuntersportal.com/" /> <title>Ghost Hunter's Portal - Admin Control Panel</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="verify-v1" content="" /> <meta name="keywords" content="ghost, hunters, hunter, ghosts, spirit, spirits, paranormal, investigation, investigator, investigators, k2, emf, meter, kii" /> <meta name="description" content="Ghost Hunters Potal. Parnormal research equipment store." /> <meta name="author" content="Andrew McCarrick" /> <meta name="robots" content="index, follow" <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <img src="./logo.png" alt="Ghost Hunter's Portal Admin Control Panel" /> <br /> <div style="color: #AA44AA; font-size: 26px; margin-top: -30px; margin-left: 125px;">Admin Control Panel</div> <?php echo $logout; echo $content; ?> </body> </html> I can log-in, and get to the page with the two links on it. However, once I click one of the links it falls back to the log-in page, and it ends up being a never ending loop. It's doing this: Log-In --> Page with links ---> Log-In page again Should be doing this: Log-In --> Page with links --> Add Product page or View Products page I can never get into the the actual sub page. Just to be clear, the address bar actually shows product=add or product=view, but it still shows the log-in page. Good Evening - I am in the process of trying to call back a list of categories and sub categories using a WHILE LOOP inside of a WHILE LOOP. It works on a different part of the site within the admin panel but not here. Here it only calls one sub category and moves on to the next parent category instead of finishing the loop and pulling all sub categories out... // CATEGORIES $query = "SELECT * FROM cat"; $result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $catid = $row['id']; $catname = $row['name']; $output .= "<li class=\"level0 nav-2 parent\" onmouseover=\"toggleMenu(this,1)\" onmouseout=\"toggleMenu(this,0)\"> <a href=\"product.php?cat=$catid\"> <span>$catname</span> </a>\n"; $querynav = "SELECT * FROM subcat WHERE pid = '$catid'"; $resultnav = mysql_query($querynav); while($array = mysql_fetch_array($resultnav, MYSQL_ASSOC)) { $subcatid = $row['id']; $subcatname = $row['name']; $output .= "<ul class=\"level0\"> <li class=\"level1 nav-2-1 first\"> <a href=\"product.php?cat=$catid&subid=$subcatid\"> <span>$subcatname</span> </a> </li> </ul> </li>"; } } Hello guys im new to php i been coding for like a week now, i need some help here i have been stuck for like 6 hours XD,is it possible to write an IF Statement inside an echo? //this is what i want to do // echo a table and a delete button // and if you click on the delete button it echoes out "DELETED" echo " <table width='528px'> <tr> <td> </td> <td> <center><font size='5'>$tittle</font></center><br> </td> </tr> <tr> <td> </td> <td> $message </td> </tr> <tr> <td> </td> <td> <font size='1'>Posted By:<font color='green'>$author</font> on <font color='gray'>$date</font> at <font color='gray'>$time</font></font> <input id='delete' name='delete' type='submit' value='Delete' > if ($_POST['delete']) { echo "DELETED"; } <td> </td> </tr><br><br> </table> "; I am wondering if it is possible to create 2 queries, and use 1 while statement? Something like: Code: [Select] while (($row = mysql_fetch_array($rs_getevent)) && ($row = mysql_fetch_array($rs_getevent2))) { Is something like this possible? I am trying to create a daily event listing. The list will have Day & Date as the heading. Then it will list the events ORDERED BY the time. First thing I'd like to do is skip or not show the days that do not have an event. Ex. Monday, January 23, 2012 7am event 8am event 6pm event since Tuesday has no events, I'd like tuesday to not be in the list, but if the next tuesday has an event It'll need be visible. Tuesday, January 24, 2012 (No events) Wednesday, January 25, 2012 9am event 12 pm event 8pm event The 2nd thing I'd like to do is If a particular day and time has more than one event, I'd like the time to show once and then list the events. ex. Monday, January 23, 2012 7am event event event 8am event 6pm event Here's the code: since the listing is for a range of 7 days I've only included 3 days worth of code. I've include the mysql_statements for pulling the information as well as the php code to show how it's being rendered and placed. HTML excluded. Code: [Select] <?php //TODAY $today2 = date('l, F j, Y');//php to format date $today_rehearsals = mysql_query(" SELECT Id, date, time, title, campus, room, ministry, category FROM events LEFT JOIN dates on events.dateId=dates.dateId LEFT JOIN time ON events.timeId=time.timeId LEFT JOIN campus ON events.campusId=campus.campusId LEFT JOIN rooms ON events.roomId=rooms.roomIdLEFT JOIN ministries on events.ministryId=ministries.ministryId LEFT JOIN category on events.categoryId=category.categoryIdWHERE ministry='music' AND date='$today' OR category='music' AND date='$today' ORDER By date, time") //////DAY ONE $day1= mktime(0,0,0, date("m"), date("d")+1, date("Y")); //php to get current date and add 1 day $day_1 = date("l, F j, Y", $day1); //php to format date $day1_rehearsal = mysql_query("SELECT Id, date, time, title, campus, room, ministry, category FROM events LEFT JOIN dates ON events.dateId=dates.dateIdLEFT JOIN time ON events.timeId=time.timeId LEFT JOIN campus ON events.campusId=campus.campusId LEFT JOIN rooms ON events.roomId=rooms.roomId LEFT JOIN ministries ON events.ministryId=ministries.ministryId LEFT JOIN category ON events.categoryId=category.categoryId WHERE ministry='music' AND date=CURDATE()+1 OR category='music' AND date=CURDATE()+1 ORDER BY time" ) or die(mysql_error()); /////DAY 2 $day2= mktime(0,0,0, date("m"), date("d")+2, date("Y")); //php to get current date and add 2 days $day_2 = date("l, F j, Y", $day2); //php to format date $day2_rehearsal = mysql_query("SELECT Id, date, time, title, campus, room, ministry, category FROM events LEFT JOIN dates ON events.dateId=dates.dateIdLEFT JOIN time ON events.timeId=time.timeId LEFT JOIN campus ON events.campusId=campus.campusId LEFT JOIN rooms ON events.roomId=rooms.roomId LEFT JOIN ministries ON events.ministryId=ministries.ministryId LEFT JOIN category ON events.categoryId=category.categoryId WHERE ministry='music' AND date=CURDATE()+2 OR category='music' AND date=CURDATE()+2 ORDER By time")or die(mysql_error()); ////TODAY echo "$today2"; //renders Today's date while($row = mysql_fetch_array( $today_rehearsals )){ $time=date_create($row['time']);//grab time for db $for_time=date_format($time, 'g:i a');//format time for viewing on page echo "$for_time"; echo $row['title']; echo $row['campus'] . " " . $row['room']; } ////day1 echo "$day_1"; //renders day_1's (tomorrow's) date while($row = mysql_fetch_array( $day1_rehearsal )){ $time=date_create($row['time']);//grab time for db $for_time=date_format($time, 'g:i a');//format time for viewing on page echo "$for_time"; echo $row['title']; echo $row['campus'] . " " . $row['room']; } ////day2 echo "$day_2"; //renders day_2's (day after tommorrow) date while($row = mysql_fetch_array( $day2_rehearsal )){ $time=date_create($row['time']);//grab time for db $for_time=date_format($time, 'g:i a');//format time for viewing on page echo "$for_time"; echo $row['title']; echo $row['campus'] . " " . $row['room']; } MOD EDIT: code tags fixed . . . Hi everyone. i'm trying to write an if statement for several scenerios 1. if the date entered in '$DateDue' is overdue, meaning greater than todays date, then display the word 'Late'. 2. if the date entered in '$DateDue' is not yet past, meaning its greater than todays date, then display the word 'ok'. 3. if the date entered in '$DateDue' is within a week of todays date, then display the word 'warning' the code snippet below is my partial script. it runs perfectly without embedding the 'php if statement' on the first td row. So my problems a 1. how to embed a php if statement in table results and 2. have OK, LATE or WARNING to be displayed based on if $DateDue expires or not. there are no errors in the code below, it just echos the line '<?php if ($DataDue > CURDATE()) {echo "OK";} elseif ($DateDue < CURDATE()) {echo "LATE";} else {echo "Warning";}?>' instead of displaying OK, LATE or Warning. I'd appreciate any assistance you could provide. thanks. Code: [Select] // echo out the contents of each row into a table echo "<tr>"; echo '<td nowrap><?php if ($DataDue > CURDATE()) {echo "OK";} elseif ($DateDue < CURDATE()) {echo "LATE";} else {echo "Warning";}?>' . mysql_result($result, $i, 'DateDue') . '</td>'; echo '<td nowrap>' . mysql_result($result, $i, 'Description') . '</td>'; echo '<td nowrap>' . mysql_result($result, $i, 'CompanyName') . '</td>'; echo "</tr>"; I have the following code which gets staff working on a selected day and their start and finish times. The code then lists out the day for every 15min of time for each staff member. During the loop of each staff member I then check an appointment table to see if a user has any appointments, and lists the booked time slots, if no appointments lists user as available for all the time slots. My problem is when a user has appointments it only shows the booked times and not the available times. I know the problem lies here else if ($inc<$resSTART && $inc>$resEND) { and the complete code that is from is here // convet to US format $input="$month/$day/$year"; // readable date $readDATE="$day/$month/$year"; // convert for mysql date $sqlDATE="$year-$month-$day"; // get day of the week $weekday=date(l, strtotime($input)); echo $weekday."<br/>"; // get working staff from staff table $staffSQL=mysql_query("SELECT * FROM staff WHERE ".$weekday." != 'off' AND onLEAVE='no' AND ACTIVE='yes' ORDER BY staffID ASC"); // return results putenv("TZ=Australia/Adelaide"); while ($staff=mysql_fetch_array($staffSQL)) { $name=$staff['staffNAME']; $avail=$staff[$weekday]; $staffID=$staff['staffID']; list($first, $last)=explode(" ", $name); list($in, $out)=explode("-", $avail); $firstTIME="$sqlDATE $in:00"; $lastTIME="$sqlDATE $out:00"; echo "$first is available between $avail on $weekday<br/>"; $in2=strtotime($firstTIME); $out2=strtotime($lastTIME); $stop=$out2-900; echo $in2." - time start - $firstTIME<br/>"; echo $out2." - time finish - $lastTIME<br/>"; for ($inc=$in2;$inc<=$stop;$inc+=900) { $existSQL=mysql_query("SELECT * FROM appointment WHERE date='$sqlDATE' AND staffID='$staffID'"); if (mysql_num_rows($existSQL)>=1) { while ($appointV=mysql_fetch_array($existSQL)) { $resSTART=$appointV['dateTIME']; $length=$appointV['totalTIME']; $resEND=$resSTART+($length*60); if ($inc>=$resSTART && $inc<=$resEND) { echo "Appointment time is ".date("g.i a", $inc)." <font color='red'><< $first BOOKED</font><br/>"; } else if ($inc<$resSTART && $inc>$resEND) { echo "Appointment time is ".date("g.i a", $inc)." <font color='green'><< $first AVAILABLE</font><br/>"; } } } if (mysql_num_rows($existSQL)==0) { echo "Appointment time is ".date("g.i a", $inc)." <font color='green'><< $first AVAILABLE</font><br/>"; } } } any ideas how to restructure that if statement to work properly would be very much appreciated I have a bunch of checkboxes I am pulling from a database, like so. Code: [Select] <?$true_query = mssql_query("SELECT * FROM checkbox_datbase ORDER BY ID ASC"); while ($true_row = mssql_fetch_assoc($true_query)) { $eth_id = $true_row['ID']; $eth_name = $true_row['Value']; echo "<input type=\"checkbox\" name=\"eth_$eth_id\" value=\"1\" class=\"input\" id=\"Ethnic_01\"/>$eth_name <br />"; } ?>How do I put these into a database that I have settup where it needs to match up with a userid. I am trying to do this, and can get it to look correctly by echoing out the various parts, but I can't put while loops into a variable, right? So how would I get all of this into one line in my $sql variable? Code: [Select] echo "INSERT INTO new_database (UserId,"; $true_query = mssql_query("SELECT * FROM checkbox_datbase ORDER BY ID ASC"); while ($true_row = mssql_fetch_assoc($true_query)) { $eth_id = $true_row['ID']; $eth_eth_id = $_POST['eth_' . $eth_id . '']; echo " $eth_id, "; } echo "DateUpdated) VALUES ('$user_ID', "; $true_query = mssql_query("SELECT * FROM checkbox_datbase ORDER BY ID ASC"); while ($true_row = mssql_fetch_assoc($true_query)) { $eth_id = $true_row['ID']; $eth_eth_id = $_POST['eth_' . $eth_id . '']; echo "'$eth_eth_id', "; } echo "'$currenttime')"; This echoes something that looks like this INSERT INTO user_ethnicity (UserId, 1, 2, 3, 4, 5, 6, 7, 8, DateUpdated) VALUES ('', '', '', '', '', '', '', '', '', '2012-01-23 13:24:18 PM') , which I need the actual statement to be $sql = "INSERT INTO user_ethnicity (UserId, 1, 2, 3, 4, 5, 6, 7, 8, DateUpdated) VALUES ('259', '', '', '1', '', '1', '', '', '', '2012-01-23 13:24:18 PM')"; Can anyone help me with this? Hey guys! Im trying to setup an IF statement on my home page. Its purpose is to show EITHER a login form and state your not logged in if it cannot find a stored cookie OR if it does find a stored cookie it will NOT show the HTML form and state you are logged in. I have it mostly working apart from the fact Im not sure how to insert a HTML form into PHP IF statement and make it work. Since I dont want the user to see the login form when they are already logged in. Here is a link to the php script: http://pastebin.com/aenq4gbE Here is link to the live page: http://jfbsystems.co.uk/secure Any help or ideas would be much appreciated! JellyFishBoy Hi I am new to PHP and this is my first post one here so appologies is this questions seems a bit dumb! I have an if clause such that if a button is pressed on my web page then i want to reload the page and include a new form on it. I am having a problem getting the $_SERVER['PHP_SELF'] command to work from iside a echo command. I must not be escaping the code correctly with back slashes: I currently have the line : echo"<form method=\"POST\" action=\"\<?$_SERVER['PHP_SELF']?\>\">"; However this doesnt seem to work as my page just doesnt display in the browser. Any advice is much appreciated. Thanks for taking the time to read. I have two tables...one is scheduled_umps and one is games. Both tables have a column 'game_id'. I need to select how many games a person is scheduled for in a given time frame. Here's what I have for the select...and it's not working (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 'WHERE scheduled_umps.ump_id = '34' AND games.game_id = scheduled_umps.game_id AN' at line 1) Code: [Select] <?php $today_is_this_date = date('Y-m-d'); $four_months_ago = date('Y-m-d', strtotime('-4 months', strtotime($today_is_this_date))); $four_months_from_now = date('Y-m-d', strtotime('+4 months', strtotime($today_is_this_date))); /// How many games have you worked? //$query = "SELECT COUNT(ump_id) FROM scheduled_umps WHERE `ump_id` = '$_SESSION[ump_id]'"; ///this one selects how many games you've worked NO MATTER WHAT THE DATE $query = "SELECT scheduled_umps.game_id, games.game_id, COUNT(scheduled_umps.ump_id) WHERE scheduled_umps.ump_id = '$_SESSION[ump_id]' AND games.game_id = scheduled_umps.game_id AND games.game_id BETWEEN $four_months_ago AND $four_months_from_now"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ echo "You have been scheduled on <b>". $row['COUNT(ump_id)'] ."</b> dates for the $_SESSION[association_name]."; } ?> [\code] Any ideas where I'm going wrong? Thanks for the help...I HATE multi-table selects! Hi, Im building a custom theme for wordpress and i need some help with a loop, its not wordpress specific code just a general if and loop. heres what i have. Code: [Select] $pages = get_pages('parent=0&sort_column=menu_order'); if ($pages) { $output=''; foreach ($pages as $page) { if($page->post_status=='publish'){ $output.='<li class=top><a href="'.$page->guid.'" class=top_link><span>'.$page->post_title.'</span></a>'; $sub_pages = get_pages( 'child_of ='. $page->ID); if ($sub_pages){ foreach ($sub_pages as $sub_page) { if($sub_page->post_status=='publish'&& $sub_page->post_parent== $page->ID) { if($sub_page->guid==" ") { } else { $output.='<ul class=sub>'; $output.='<li><a href="'.$sub_page->guid.'">'.$sub_page->post_title.'</a></li>'; $output.='</ul>'; } } } }} $output.='</li>'; } } What im trying to do is only echo <ul class=sub> and the inside <li> if there is something in sub_page guid. I managed to build this code and it works, but i need to move the <ul></ul> outside of the loop so it doesnt repeat over and over again, but i also dont want it being echoed if sub_page->guid is empty sorry for my poor explanation im doing the best i can. Thanks in advance for any help |