PHP - Single Result Sql Code
At present, all my queries return multiple records. Now I want to do a record count, and only return the one record.
Current Code Code: [Select] $query = "SELECT * FROM tblListField WHERE ListID = '" . $_SESSION['listid'] . "'"; $result = mysqli_query($dbc, $query) or die('Error executing SELECT * statement for tblListField - ' . $query); if(mysqli_num_rows($result)) { // at least one row, process the data from the query while ($row = mysqli_fetch_array($result)) { So the above runs through each record; what do I use to get the one record from the following SQL? (Note; I'm using mysqli_) Code: [Select] $query = "SELECT COUNT(ItemField_1) WHERE ListID='" . $listid . "'"; Similar TutorialsQuote from: Hollows on August 20, 2010, 11:29:25 AM I have an array that is pulling 10 results from a db like this - <?php $result = mysql_query("SELECT * FROM inbox ORDER BY id DESC LIMIT 0,10"); while ($row = mysql_fetch_array($result)) { <div class="<?php echo $row['class']; ?>"> <?php echo $row['name']; echo $row['message']; ?> </div> basically 'class' is defined in an earlyier part of the script and is used to tell the css what class to display - as I'm sure you can see. What I'd like todo then be able to update the class of a message once I have read it, so update the class table with something like 'read' so the css will then be based on .read not what ever was set by the form, either using a link or form button inside each of the 10 results from the array. I've managed to update one by using - Code: [Select] mysql_query("UPDATE shoutbox SET class = 'read' WHERE id = ''XX"); // XX should be row id But I had to set that myself and point the id to the row id I wanted to change - How can I have that already populated with the row for the id that triggered it? To be clear so it looks like - Name Message read button _____________ Name Message read button _____________ Name Message read button _____________ and so on... Would I be better going by check boxes and one submit button? If so how could I implement that? I can provide the full code I've written if it helps Thank you in advance Hi all, Just to check if it is possible to have 2 while loops in a single code? Below are my codes. SQL code $tutor_id = mysqli_real_escape_string($dbc, $_GET['tutor_id']); $query = "SELECT tl.level_id, tl.level_name, ts.subject_id, ts.subject_name, tsl.subject_level_id, IF(tosl.tutor_id='{$tutor_id}', 1, 0) as checked FROM tutor_level AS tl INNER JOIN tutor_subject_level AS tsl USING (level_id) INNER JOIN tutor_subject AS ts USING (subject_id) LEFT JOIN tutor_overall_level_subject AS tosl ON tosl.subject_level_id = tsl.subject_level_id AND tosl.tutor_id = '{$tutor_id}' ORDER BY tl.level_id, ts.subject_name"; $sql = mysqli_query($dbc, $query) or die(mysqli_error($dbc)); $query1 = "SELECT tl.level_id, tl.level_name, IF(tslvl.tutor_id='{$tutor_id}', 1, 0) as checked FROM tutor_level AS tl LEFT JOIN tutor_selected_level AS tslvl ON tslvl.level_id = tl.level_id AND tslvl.tutor_id='{$tutor_id}' ORDER BY tl.level_id, tl.level_name"; $sql1 = mysqli_query($dbc, $query1) or die(mysqli_error($dbc)); PHP code (2 while loops) //Process the results $checkboxes = ''; //Create variable for output $current_level_id = false; //Flag to check when records change level while($data = mysqli_fetch_array($sql)) //Iterate throug the DB results { if($current_level_id != $data1['level_id']) //Determine if this level is different from the last { print_r ($data); $checkboxes .= createLevelCheckboxes($subject_data, $level_data, 5); $current_level_id = $data['level_id']; $subject_data = array(); } //Add the current record to the $level_data array $subject_data[] = $data; } //$checkboxes .= createLevelCheckboxes($subject_data, $level_data, 5); while($data1 = mysqli_fetch_array($sql1)) { print_r ($data1); $checkboxes .= createLevelCheckboxes($subject_data, $level_data, 5); $level_data = array(); $level_data[] = $data1; } //Call the createLevelCheckboxes() function to generate the HTML for the LAST level records $checkboxes .= createLevelCheckboxes($subject_data, $level_data, 5); hello. I have some oop code that pulls information about a page out of a mysql db but i dont want to put the code on every page. Instead in want to put it in the a function and pass it back to each page. do i put it in a function in my functions.php file or can i put it into my includes/pages.php includes file ?? the code looks for the page name on the page and then pulls that pages info from the db. this code works on the page - home.php Code: [Select] <?PHP require_once("../includes/initialize.php"); $currentPages = Pages::find_all(); $pName = "adminHome"; $page_id = ""; $visible = ""; $pageZones = ""; $pageCRUD = ""; $pageTypes = ""; $module = ""; $title = ""; $sub_title = ""; $description = ""; $image = ""; $about = ""; foreach($currentPages as $currentPage){ $page_id = $currentPage->id; $pageName = $currentPage->pageName; $visible = $currentPage->visible; $pageZone = $currentPage->pageZones_id; $pageCRUD = $currentPage->pageCRUD_id; $pageType = $currentPage->pageTypes_id; $module = $currentPage->module_id; $title = $currentPage->title; $sub_title = $currentPage->sub_title; $description = $currentPage->description; $image = $currentPage->image; $about = $currentPage->about; if($pageName == $pName){ echo $pageName.'<br/>'; echo $page_id.'<br/>'; echo $visible.'<br/>'; echo $pageZone.'<br/>'; echo $pageCRUD.'<br/>'; echo $pageType.'<br/>'; echo $module.'<br/>'; echo $title.'<br/>'; echo $sub_title.'<br/>'; echo $description.'<br/>'; echo $image.'<br/>'; echo $about.'<br/>'; } } ?> i would like to be able to just put global $page or something like that to get all the db info for each page. i tried this in my includes/pages.php includes file but it cant get the page name. Code: [Select] public static function find_by_pageName(){ global $database; global $pName; $sql = "SELECT * FROM ".self::$table_name." WHERE pageName=".$pName.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } any suggestions ???? whats the best way to do this ? thanks ricky Hey Everyone, I am posting today because I have a site I am working on which uses the xzero classifieds and having a small problem accomplishing something with it. I am trying to relocate the ad count number (of the city the user is currently browsing) to a box in my sidebar which has various site statistics like the following Online Users: XX Ads in this city: 0 But my code keeps giving me a 0 (even after I posted some test ads) Anywho, heres what I have so far but cant seem to make it work <?php $country_adcounts = array(); $city_adcounts = array(); $sql = "SELECT ct.cityid, c.countryid, COUNT(*) as adcnt FROM $t_ads a INNER JOIN $t_cities ct ON ct.cityid = a.cityid AND ($visibility_condn) INNER JOIN $t_countries c ON ct.countryid = c.countryid WHERE ct.enabled = '1' AND c.enabled = '1' GROUP BY ct.cityid"; $res = mysql_query($sql) or die(mysql_error().$sql); while($row=mysql_fetch_array($res)) { $country_adcounts[$row['countryid']] += $row['adcnt']; $city_adcounts[$row['cityid']] += $row['adcnt']; } $adcount = 0+$city_adcounts[$city['cityid']]; ?> and this is the code which should recall the adcount <?php echo $adcount; ?> What am I doing wrong? I'm placing the first code on my sidebar and attempting to call the ad count through an echo. So ya, if anyone could tell me why this isn't working or lend a hand in helping me fix it please know I'll greatly appreciate it. Thanks. I have a database that contains results of fantasy football games. I have a query that returns the results of the games team X played against the other teams in the league. The query works perfect in the database. Results are Quote Opponent Name: America Enforcers Wins Losses Draws 1 1 0 Last Game: Week 2 of 2011: 416.6 - 369.8 the query and the php code cycle thru each team that team X has played and brings up team X's record and the results of the last game played. My problem is that the code stops one team short. So Team X played teams A, B, C, D, E but the code only returns teams A, B, C, D E is left off. I can't for the life of me figure out what silly mistake I made. Code: [Select] <?php include_once('../other/functions.php'); $con = mysql_connect($hostname, $username, $password) OR DIE ('Unable to connect to database! Please try again later.'); $db = mysql_select_db($dbname, $con); $thing = $_GET['thing']; $query = "select selected.teamname AS selected_team, selected_score.score AS selected_score, week.week, year, home_id, ". "target_score.score as target_score, target.teamname as targetname, week.ID ". "from owners as selected ". "JOIN game_scores AS selected_score ON selected.owner_id = selected_score.team_id ". "JOIN game_setup ON game_setup.game_id = selected_score.game_id ". "JOIN game_scores AS target_score ON target_score.game_id = game_setup.game_id AND target_score.team_id != selected_score.team_id ". "JOIN owners AS target ON target.owner_id = target_score.team_id ". "JOIN week ON week.week = game_setup.week ". "WHERE selected.owner_id = $thing ". "and target.active = 1 ". "GROUP BY target.teamname, year, week.ID "; $result = mysql_query($query); $row = mysql_fetch_array($result); $result1 = mysql_query($query); $row1 = mysql_fetch_array($result1); if (!$result) { die('Invalid query: ' . mysql_error()); } $wins=0; $losses=0; $draws=0; $last_target = false; echo '<h2>' . $row1['selected_team'] . ' vs. Active Teams</h2>'; while ($row = mysql_fetch_assoc($result)) { if ($last_target['targetname'] != $row['targetname']) { if ($last_target) { printf(' <table border="1" width="600"> <tr> <th>Opponent Name:</th> <th colspan="2">%s</th> </tr> <tr> <th>Wins</th> <th>Losses</th> <th>Draws</th> </tr> <tr> <td align="center">%d</td> <td align="center">%d</td> <td align="center">%d</td> </tr> <tr> <th>Last Game:</th> <td colspan="2">%s of %s: %.1f - %.1f</td> </tr> </table><br/>', $last_target['targetname'], $wins, $losses, $draws, $last_target['week'], $last_target['year'], $last_target['selected_score'], $last_target['target_score'] ); } $wins = $losses = $draws = 0; } if ($row['selected_score'] < $row['target_score']) ++$losses; elseif ($row['selected_score'] == $row['target_score']) ++$draws; else ++$wins; $last_target = $row; } ?> Any ideas on how to make the magic elvish be good??? Thank you for your time. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=343031.0 PHP script return 20Â UL LISTÂ values like, < ul >
A < /ul > How to display UL LIST into row wise 5 columns like
A B C D Hi, I've been scratching my head for a while now about how to do this, I'm relatively new to php and mysql and perhaps foolishly taking on creating a user area for a website. I have everything else working, all of my register account functions and confirmations and all of the login scripts etc. I have created a profile page which returns various information to the user (this bit works fine) and I've got some nice show/hide toggles running with some javascript/css but my intention is to allow the user to change thier information (e-mail address, contact phone number and also whether they are subscribed to the e-mail list), it also displays any support tickets or messages. So after the long intro, here's what I'm struggling with... I have a form in a visibility toggled <div> which submits a 'change_email' script, so a user wants to change their e-mail, clicks on change, the <div> appears, they bang in the new e-mail and hit submit. My php script appears to work (because it doesn't throw up any errors), until you realise that actually it's not updated the record in the db... I'm using mysql_query("UPDATE users SET email='$new_email' WHERE username='$user'"); Do I need to setup variables for all of the information in the db (name, username, password, email, contno etc etc) and include them in the command to get it to work or should that just pick the correct record and then update it? If that is the case is there a way I can include 'blank' variables so I don't have to set them all up... e.g. mysql_query("UPDATE users SET user='',password='',email='$new_email', etc WHERE username='$user'"); Many thanks in anticipation I am really lost here with this date issue of mine. The below code is the last part of a query: Code: [Select] $defendercheck_3 = $row_checkifattacked3['atdate']; $defendercheck1_3 = strtotime("$defendercheck_3"); $defendercheck2_3 = date("D", $defendercheck1_3); The query does not return any results as expected, but when echoing the various steps I get following: echo "$defendercheck3"; = nothing (as expected) echo "$defendercheck1_3"; = nothing (as expected) echo "$defendercheck2_3"; = result! (NOT expected) why does it return anything on "date("D", $defendercheck1_3)" when "$defendercheck1_3" is blank? Hi, I'm trying to delete a string that's single quoted. From: Cyto's to Cyto, but doesn't work. It works when I add 's to the string with stripslashes, but I can't seem to delete a quote from a string. Does someone know how? My $_post code: Code: [Select] $name=mysql_real_escape_string(stripslashes($_POST["ename"])); Cheers How to pull just I record of a column out of the 20 columns? This is not showing the results. $SomeVar = 'pets'; $query = "SELECT field1 FROM db1 WHERE id1 = '".$SomeVar."'"; $results=mysql_query($link); echo $link; So I'm rebuilding an existing joomla component in laravel and this time I want to get it right. Hopefully my explanation is not too complicated.
I have this situation:
I have an order. The order has many products. The product has many parameters in the form of input fields such as radio, select list and text (think of color, size, engraving, logo select). An order also has some parameters such as address etc.
My question is how I should structure this considering the following:
1. The parameters of either an order itself or a product can change from time to time. Sometimes I need to add several fields for a certain amount of time.
2. Each product has 1 or more production pages (production steps) where some of the parameters set by the order need to be visible. Each production step has its own set of parameters (3d model, logo file). This means that the step1 page should show its own parameters INCLUDING a predetermined set of product parameters. So the columns could look like this: color - engraving - logo select - 3d model - logo file.
3. Each production page lists all the products belonging to that step.
4. Each product can belong to 1 or more production steps.
5. A product is only visible at 1 step at a time. The steps have a specific ordering.
A little note: it's not a usual webshop, but rather we sell custom sports products. Currently we have 3 products where 1 product has 2 production steps and another has 3 production steps.
Don't get me wrong, I have a working application for this, but currently it's just a database mess. The application kept growing as per bosses request so thinking it through was not possible at the time.
I can use the first while loop, but there is no data in the second while loop. Is there a better way as I have never done this before... Code: [Select] <?php $featured_results = mysql_query("SELECT * FROM products LEFT JOIN product_images ON products.product_id=product_images.product_id WHERE products.product_featured='1' AND products.product_active='1' AND thumb='1'"); $fa=0; while($featured_row = mysql_fetch_assoc($featured_results)) { $fthumb_result = mysql_query("SELECT image_name FROM product_images WHERE product_id='".$featured_row['product_id']."' AND thumb='1'"); $fthumb = mysql_fetch_row($fthumb_result); if ($fa==0) { echo "\n<img id=\"home-slider-photo-".$fa."\" class=\"home-slider-photo preload\" src=\"/includes/getimage.php?img=".$fthumb[0]."&w=370&h=370\" alt=\"\" />"; } else { echo "\n<img id=\"home-slider-photo-".$fa."\" class=\"home-slider-photo preload home-slider-photo-unsel\" src=\"/includes/getimage.php?img=".$fthumb[0]."&w=370&h=370\" alt=\"\" />"; } $fa++; } echo "<div id=\"home-slider-photo-price\">"; $fb=0; while($featured_row2 = mysql_fetch_assoc($featured_results)) { if ($fb==0) { echo "\n<div id=\"home-slider-photo-price-".$fb."\" class=\"home-slider-photo-price\">\n<span>only</span>$".$featured_row2['product_price']."\n</div>"; } else { echo "\n<div id=\"home-slider-photo-price-".$fb."\" class=\"home-slider-photo-price home-slider-photo-price-unsel\">\n<span>only</span>$".$featured_row2['product_price']."\n</div>"; } $fb++; } echo "</div>"; ?> I need to get the 2nd code working. Please help. This works $query = "SELECT DISTINCT addressz FROM abs WHERE statez = 'AZ'"; $results = mysql_query($query); But this dosen't. $SomeVar = $_POST['disloc']; $query = "SELECT DISTINCT addressz FROM abs WHERE statez = '".$SomeVar."' ORDER BY addressz ASC"; $results = mysql_query($query); Greetings, I'm trying to execute a shell command with a user-supplied password as input. The password may contain apostrophes and and virtually any other character. Unfortunately, when using escapeshellarg(), the password argument is interpreted as two separate arguments, as escapeshellarg() will handle apostrophes (single quotes) by breaking out of the already quoted text and using a backslash escape. $password = escapeshellarg("ex'ample!%"); // The password will actually be supplied by an HTML form. $command = ('echo '.$password); echo "$command"; // Returns 'ex'\''ample!%' Does anyone have any input on how to accomplish what I'm trying to do? I'd like to allow obscure passwords without disallowing specific characters, while still being "safe" in passing the information to a shell command. Double quotes would work for passing single quotes, but I'm afraid I might break other characters there. Thanks. Hay wut's happening forum? so i am currently working on a mailing list and its function is to send EVERY single user a notification email once an entry they are looking for on a database is available below is the mailing_list.php which sets up database connection and deals with the fields of the table: <?php include('view_function.php'); global $connect; $connect = mysqli_connect("localhost", "", "") or die(mysqli_error($connect)); $error = mysqli_error($connect); $db_select = mysqli_select_db($connect, ""); $select5 = "SELECT LS_CELL_TYPE FROM link_specificities INNER JOIN links ON link_specificities.LS_LINK = links.L_ID WHERE links.L_ID = $LinkID"; $get5 = mysqli_query($connect, $select5) or die(mysqli_error($connect)); while ($row5 = mysqli_fetch_array($get5)){ extract($row5); $cellType = $row5['LS_CELL_TYPE']; } $select6 = "SELECT CT_NAME FROM cell_type WHERE CT_ID = '$cellType'"; $get6 = mysqli_query($connect, $select6) or die(mysqli_error($connect)); $i = 0; while ($row6 = mysqli_fetch_array($get6)){ extract($row6); $query[$i] = $row6['CT_NAME']; $check = "select first_name, email from mailing_list WHERE query = '$query[$i]'"; $i++; echo $query; } update($check); ?> And below is the view_function.php that's included above: <?php function update($check){ global $query; global $connect; global $LinkID; $result = mysqli_query($connect, $check) or die(mysqli_error($connect)); while ($row3 = mysqli_fetch_array($result)){ extract($row3); $fname = $row3['first_name']; $email = $row3['email']; $to = "$fname <$email>"; $subject = "The query is updated."; $headers = "From: asdfasdfasdf"; $body = " Hello $fname,\r\n\nThis is to inform you that $query is updated, please go to this link to search for it:\r\n\nhttp:/asdfasdfasdfasdf/view/View.php?LinkID=$LinkID \r\n\nRegards,\r\n\"; if(send_email($to,$subject,$body,$headers)){ //there are no errors, return empty array $errors = array(); } else { $errors[] = "Server error, mail could not be sent."; } } } ?> As you can c in mailing_list.php, i echoed out $query, but it only echoed ONE result of that entire array so wut i am trying to do is to make a while loop with a counter in it, but still only one result shows up Basically, i want the $query to output all items in an array so that following SELECT statement can choose the item which matches the required query and send the users the notification email bout such particular query How should i fix it in order to do just that? thanks I was talking to some friends, who are just as new as me in programming, and they think it would be better to use a single navigation file for every link in a web site. Something like this: Code: [Select] <a href="nav.php?id=home&otherparams" >Home</a> <a href="nav.php?id=products&otherparams" >Products</a> <a href="nav.php?id=contact&otherparams" >Contact</a> I told them I think this might be easier to maintain, but also might take up on loading time, as the site viewer will have to go through an extra node to get where he wants. Is this single navigation file a good practice or should it be avoided? Thanks for any comments... This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=358810.0 Hi All Sorry my first post is a help one... I'm developing a small fault logging application I need a little help with. This is my code at the moment Client Table Columns contractid, company, branch, addressline1, addressline2, addressline3, addressline4, postcode, contactname, telephone, email Addressbook2 Table Columns nameid, namecompany, namecontactname, nameaddressline1, nameaddressline2, nameaddressline3, nameaddressline4, namepostcode, nametelephone1, nametelephone2, nameemail, <?php $NodeTitles = mysql_query("SELECT * FROM faults, users, clients, addressbook2 WHERE faults.client = clients.contractid AND faults.referredby = addressbook2.nameid AND faults.openedby = users.userid ORDER by dateopened DESC, timeopened DESC") or die (mysql_error()); while ($row = mysql_fetch_assoc($NodeTitles)) { ?> <tr id="entryRow2358" onMouseOver="this.style.cursor='pointer'" onclick="window.location.href='job.php?faultid=<?php echo $row['faultid'];?>';"> <td class="n" colspan="1"><div title=""><?php echo $row['faultid'];?></div></td> <td class="" colspan="1"><div title="Company"><?php echo $row['clientcompany'];?></div></td> <td class="" colspan="1"><div title="Referrer"><?php echo $row['referrercompany'];?></div></td> <td class="" colspan="1"><div title="Branch"><?php echo $row['clientbranch'];?></div></td> <td class="" colspan="1"><div title="Fault"><?php echo $row['fault'];?></div></td> <td class="" colspan="1"><div title="Opened By"><?php echo $row['fullname'];?></div></td> <td class="" colspan="1"><div title="Date Created"><b><?php $date = date_create($row['dateopened']); echo date_format($date, 'j F Y');?></b> <span><?php echo $row['timeopened'];?></span></div></td> </tr> <?php } ?> QUESTION TIME I want to make this much cleaner and tidier (and also more future proof) by removing the clients table so that I only have one 'addressbook' (this will contain clients, referrers, engineers ... and any other correspondents) Naturally I will have a column in the address book to tell me what type of correspondent the name is. ie. 1 = Client, 2 = Referrer, 3 = Engineer. So.......will I have to do many MYSQL queries within a while statement or will I be complicating the entire process by doing this? Can I write a single SQL statement to do this? Any advise or help with my code would be great! Thanks Andrew |