PHP - Select Distinct Field
Hello.
I am trying to display only one instance of records that have the same memberid in my db. I am using the following statement but it continues to show all of the records that have the same memberid. Any ideas what I may be doing wrong? Code: [Select] $sql = "select DISTINCT memberid, event, category, date, enddate, locality, location, address, city, state, zip, contact, phone, notes, doc1, doc2, doc3, doc4, doc5 from event where date >= '$datenow' ORDER by date ASC"; Thanks for any help! Similar TutorialsHi am having a few problems solving this code with select distinct clause. None of what i tryed works. Can anyone help please thanks. this is just some of the query's i tryed $query7 = yasDB_select("SELECT DISTINCT * FROM useronline WHERE id;"); $query7 = yasDB_select("SELECT DISTINCT ip FROM useronline WHERE id;"); $query7 = yasDB_select("SELECT DISTINCT ip FROM useronline WHERE ip;"); $query7 = yasDB_select("SELECT DISTINCT ip,timestamp FROM useronline WHERE id;"); $query7 = yasDB_select("SELECT DISTINCT id,ip,timestamp FROM useronline WHERE id;"); $query7 = yasDB_select("SELECT DISTINCT ip FROM useronline;"); and again but without ";" $query7 = yasDB_select("SELECT DISTINCT * FROM useronline WHERE id"); $query7 = yasDB_select("SELECT DISTINCT ip FROM useronline WHERE id"); $query7 = yasDB_select("SELECT DISTINCT ip FROM useronline WHERE ip"); $query7 = yasDB_select("SELECT DISTINCT ip,timestamp FROM useronline WHERE id"); $query7 = yasDB_select("SELECT DISTINCT id,ip,timestamp FROM useronline WHERE id"); $query7 = yasDB_select("SELECT DISTINCT ip FROM useronline"); this is the code am working on. Code: [Select] $query7 = yasDB_select("SELECT DISTINCT * FROM useronline WHERE id;"); $visitors_online = $query7->fetch_array(MYSQLI_ASSOC); $visitors_online = $query7->num_rows; $query7->close(); visitors online : <?php echo $visitors_online;?><br/> How can I stop duplication in the below code? Where do I implement the DISTINCT function? $sql="SELECT * FROM ((resource l inner join resource_skill ln on l.Resource_ID = ln.Resource_ID) inner join skill n on ln.Skill_ID = n.Skill_ID) WHERE First_Name LIKE '%" . $name . "%' OR Last_Name LIKE '%" . $name ."%' OR Skill_Name LIKE '%" . $name ."%'"; //-run the query against the mysql query function $result=mysql_query($sql); //-create while loop and loop through result set while($row=mysql_fetch_array($result)){ $First_Name =$row['First_Name']; $Last_Name=$row['Last_Name']; $Resource_ID=$row['Resource_ID']; //-display the result of the array echo "<ul>\n"; echo "<li>" . "<a href=\"a.php?id=$Resource_ID\">" .$First_Name . " " . $Last_Name . "</a></li>\n"; echo "</ul>"; } } I have 5 entries in a table Code: [Select] $sql = "select count(distinct columnName) from table"; $result = mysql_result($sql); $count = mysql_fetch_array($result); echo $count[0];The output is 5 as expected. Code: [Select] $sql = "select distinct columnName from table"; $result = mysql_result($sql); $count = mysql_fetch_array($result); echo $count[0];the ouput is the first file name as expected, however Code: [Select] echo $count[1];gives undefined offset 1, which does not make any sense. Can anyone explain why the offset 1 is undefined if the count is 5? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=343149.0 So, I've been trying to get this query working and can't quite get it to work. I'm trying to get an "array" of distinct browsers from the database, but it's only showing one of them. There are 3 unique browsers in the table and only "Chrome 30" gets returned. Here is the query:
SELECT DISTINCT `browser` AS `unique_browsers`, COUNT(DISTINCT `ip`) AS `unique_visitors`, COUNT(DISTINCT `country`) AS `unique_countries`, COUNT(`id`) AS `total_count`, (SELECT COUNT(`id`) FROM `table` WHERE `browser` LIKE '%Chrome%') AS `chrome_count`, (SELECT COUNT(`id`) FROM `table` WHERE `browser` LIKE '%Internet Explorer%') AS `ie_count`, (SELECT COUNT(`id`) FROM `table` WHERE `browser` LIKE '%Firefox%') AS `firefox_count`, (SELECT COUNT(`id`) FROM `table` WHERE `browser` LIKE '%Safari%') AS `safari_count`, (SELECT COUNT(`id`) FROM `table` WHERE `browser` LIKE '%Opera%') AS `opera_count`, (SELECT COUNT(`id`) FROM `table` WHERE `browser` NOT LIKE '%Chrome%' AND `browser` NOT LIKE '%Internet Explorer%' AND `browser` NOT LIKE '%Firefox%' AND `browser` NOT LIKE '%Safari%' AND `browser` NOT LIKE '%Opera%') AS `unknown_count` FROM `table` GROUP BY `browser`Everything works properly except the line: Hi guys, using the code below within an admin panel to create a drop down allowing the user to select the profiles they wish to assign to the record they're creating, problem we have is that once a record is created, if they need to edit it for what ever reason the selected profile option isn't sticking. I've played around with lots of variants of if existing_record to try and get it add selected="selected" into the code but failed at every attempt, any advice gratefully received. Code: [Select] <?php // List only breeder profiles in the database echo '<select name="profile" class="textinput noborder">'; echo '<option value="any">Any</option>'; $qryGetDistinctProfile = "SELECT * FROM profiles ORDER BY title ASC"; $resGetDistinctProfile = mysql_query($qryGetDistinctProfile,$connection) or die(mysql_error()); if(mysql_num_rows($resGetDistinctProfile) > 0){ $id = mysql_result($resProfile, 0, "id"); while ($row = mysql_fetch_assoc($resGetDistinctProfile)){ echo '<option value="'.$row['id'].'" >'.$row['title'].'</option>'; } } echo '</select>'; ?> Hi: I have the foll. code. The table "Reports" has multiple records for a given value of CID in the Field CID. I'd like to be able to select only 1 of them so that a list of customers appearing in the Reports table is available for selection in the dropdown alphabetically. The foll. code does it but it doesnt list the Customers alphabetically. And when I use Join, the query doesnt run. I get a blank list . The Field CID is common to both tables- Reports and Customers. Could someone help me with the Join ? Thanks. Swat Code: [Select] <?php $sqlco = "SELECT DISTINCT CID FROM `Reports` "; $resultco = mysql_query($sqlco) or die (mysql_error() ) ; if ($myrowco = mysql_fetch_array($resultco) ) { do { $cid = $myrowco["CID"]; $sqlrep = "SELECT * FROM `Customers` WHERE `CID` = '$cid' " ; $resultrep = mysql_query($sqlrep) or die (mysql_error() ) ; $myrowrep = mysql_fetch_array($resultrep); $company = $myrowrep["Company"]; printf("<option value=%d> %s , %s", $myrowco["CID"], $myrowrep["Company"], $myrowco["Mdate"]); } while ($myrowco = mysql_fetch_array($resultco)); } else { echo "No records found." ; } ?></select></a> What i tried was this : Code: [Select] <?php $sqlco = "SELECT DISTINCT CID FROM `Reports` r JOIN `Customers` c WHERE r.CID = c.CID ORDER BY c.Company asc "; $resultco = mysql_query($sqlco) or die (mysql_error() ); if ($myrowco = mysql_fetch_array($resultco) ) { do { printf("<option value=%d> %s ", $myrowco["CID"], $myrowco["Company"]); } while ($myrowco = mysql_fetch_array($resultco)); } else { echo "No records found." ; } ?> This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=322629.0 Hello folks,
In trying to improve the user experience for my first WebApp I have decided to create two new tables - one a master file to contain a list of all stores, and the second a master file to contain a list of all products that are normally purchased - and I would like to use the values from these two tables as lookup values in dropdown listboxes, to which the user can also add new entries.
As it turns out, I'm stuck on the very first objective i.e. to lookup/pull-in the distinct values from the master tables.
The problem I'm having is that the query seems to return no rows at all...in spite of the fact that there a records in the table, and the exact same query (when run within the MySQL environment) returns all the rows correctly.
Is there something wrong with my code, or how can I debug to see whether or not the query is being executed?
Objective # 2, which is to allow new values to be entered into the dropdown listbox, and then inserted into the respective table is certainly waaay beyond my beginner skills, and I'll most certainly need to some help with that as well..so if I can get some code/directions in that regard it will be most appreciated.
Thank you.
<?php $sql = "SELECT DISTINCT store_name FROM store_master ORDER BY store_name ASC"; $statement = $conn->prepare($sql); $statement->execute(); $count = $statement->rowCount(); echo $count; // fetch ALL results pertaining to the query $result = $statement->fetchAll(); echo "<select name=\"store_name\">"; echo '<option value="">Please select...</option>'; foreach($result as $row) { echo "<option value='" . $row['store_name'] . "'></option>"; } echo "</select>"; ?> I am trying to print the list of a table which I requested with "SELECT DISTINCT" as below Code: [Select] $db_connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $sql_get = "SELECT DISTINCT category FROM con"; $sql_run = mysqli_query($db_connect, $sql_get) or mysqli_error($db_connect); $sql_assoc = mysqli_fetch_assoc($sql_run); What is now needed to print the list of the table data by this conditions? I tried the while loop, but I seem to approach wrong, and get endless loops or errors. Hi. I have two select fields one called category and the other sub category. Both are in the format. <select name="category" value=" <?php $qGetCat = "SELECT * FROM club_category" ; $rGetCat = mysql_query($qGetCat); while ($Cat = mysql_fetch_assoc($rGetCat)) { ?>" /> <option value="<?php echo $Cat['categorys'];?>"><?php echo $Cat['categorys']; ?></option> <?php } ?> </select> <select name="sub_category" value=" <?php $qGetSubCat = "SELECT * FROM sub_categorys" ; $rGetSubCat = mysql_query($qGetSubCat); while ($SubCat = mysql_fetch_assoc($rGetSubCat)) { ?>" /> <option value="<?php echo $SubCat['sub_categorys'];?>"><?php echo $SubCat['sub_categorys']; ?></option> <?php } ?> </select> Now I want to make it so that when a particular category is chosen for example self defence. The sub category when clicked shows all the self defence stuff. If watersports was chosen sub category would show things like swimming. What do I need to look up to do this? At the minute there is no link the way I have coded these to fields. In the database its self there is a; category table with categoryID and category_name sub category table with sub_cat_name and categoryID I think this will work but I have never done this so its making my head hurt just thinking about it. Does anyone have any advice, tuts or scripts to do this? Thank you I want to select the user from super_administrators, administrators, teachers and students, and give the user permission based from what table he "came". But is giving the "Query failed" error... Code: [Select] <?php //Start session session_start(); //Include database connection details require_once('../config/config.php'); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $email = clean($_POST['email']); $password = clean($_POST['password']); //Input Validations if($email == '') { $errmsg_arr[] = 'O campo Email nao foi preenchido.'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'O campo Senha nao foi preenchido.'; $errflag = true; } //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } //Create query $qry = "SELECT * FROM super_administrators,administrators,teachers,students WHERE email = '$email' AND passwd = '".md5($_POST['password'])."'"; $result = mysql_query($qry); $member = mysql_fetch_assoc($result); $table = mysql_field_table('$result', '0'); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { if($table == 'super_administrators') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/sadmin/index.php"); exit(); } if($table == 'administrators') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/admin/index.php"); exit(); } if($table == 'teachers') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/prof/index.php"); exit(); } if($table == 'students') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_CLASS_ID'] = $member['class_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_REGISTRATION'] = $member['registration']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/aluno/index.php"); exit(); } } else { $errmsg_arr[] = 'Suas informacoes de login estao incorreta. Por favor, tente novamente.'; $errflag = true; $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } } else { die("Query failed"); } ?> Can anybody clarify the usefulness of "AS" and elaborate on how it operates. If I select a 'bananas' AS 'yeelow fruit' will it change the TITLE in the table? Or the table that is being viewed? If I dump a list of 'FRUITS' into and HTML table, will using AS rename each column for me, or is that handled by MY coing of the HTML table? Hello, i am trying to get my form to list usernames ascending as an option, but the select field just returns blank. Here is my code: Code: [Select] /** * editUserForm - Displays the users database table in * a nicely formatted field table. */ function editUserForm(){ $q = "SELECT * " ."FROM ".TBL_USERS." ORDER BY username ASC"; $result = $database->query($q); while ($row = mysql_fetch_assoc($result)) { echo '<option value="'.$row["username"].'">'.$row["username"].'</option>'; } } Code: [Select] <form action="/" method="post"> <div class="column"> <p> <select name="user" id="user" placeholder="Select A User To Edit" class="{validate:{required:true}}"> <option>Select A User To Edit</option> <? editUserForm(); ?> </select> </p> <div class="action_bar"> <input type="submit" class="button blue" value="Submit Post" /> <a href="#modal" class="modal button">Cancel</a> </div> </form> All help is appreciated Hi Guys, Can someone please help me before I kill myself! I have a table holding details of images to be displayed in a gallery. The table has columns as 'id', 'image_caption', 'file_path', and 'userid'. The 'id' column is the unique key, and the 'userid' column is obviously id of the user who uploaded the image. What I would like to do is select and display one image from each unique userid and then display each image along with the details in my gallery. It doesn't really matter which users image is selected aslong as there is only one for each unique user. I have been trying a number of ways to do this (DISTINCT / subqueries) but I just cant get anything to work. Could someone please advise me on how I could get this to work. Cheers in advance.
Hi guys, <form id='contact-form".$KitchConfigID."' name='contact-form".$KitchConfigID."' action='_pages/_kitchenconfig/adm_saveKitchConfig.php?Nav=".$NavHash."&kcid=".$KitchConfigID."' method='POST'> <div class='row'> <div class='col-sm-12'> <div class='md-form mb-0 form-sm'> <input value='".$KitchConfig."' type='text' id='configname".$KitchConfigID."' name='configname".$KitchConfigID ."' class='form-control'> <label for='configname".$KitchConfigID ."' class=''>Config Name:</label> </div> </div> </div> <div class='row'> <div class='col-sm-12'> <div class='md-form mb-0 form-sm'> <select id='designer_".$KitchConfigID."' name='designer_".$KitchConfigID."' class='mdb-select md-form' searchable='Search here..' onchange='changeInput(this.value, ".$SelField.");'>"); $designersql = "SELECT * FROM `tbl_contacts` ORDER BY `FirstName`"; $resultdesigner = $conn->query($designersql); if ($resultdesigner->num_rows > 0) { $resultdesigner->MoveFirst; echo("<option value='designer_".$KitchConfigID."'></option>"); while($rowdesigner = $resultdesigner->fetch_assoc()) { $DesignerName = $rowdesigner["FirstName"]." ".$rowdesigner["LastName"]; $DesignerID = $rowdesigner["ContactID"]; if($rowdesigner["ContactID"]==$rowkitch["Designer"]){ echo("<option value='".$DesignerID."' selected='selected'>".$DesignerName."</option>"); } else { echo("<option value='".$DesignerID."'>".$DesignerName."</option>"); } } } echo("</select> <input type='text' name='".$SelField."' value='' /> <label for='designer_".$KitchConfigID."' class=''>Designer:</label> </div> </div> </div> <div class='md-form mb-0 float-right'> <button type='submit' class='btn btn-outline-danger waves-effect btn-sm float-right'>Save <i class='fas fa-magic ml-1'></i></button> </div>
$upd_KitchConfigID = $_GET["kcid"]; if(isset($_POST["configname$upd_KitchConfigID"])) { $upd_KitchConfig = $_POST["configname$upd_KitchConfigID"]; } else { $upd_KitchConfig = 'NotSet'; $ErrMsg = $ErrMsg . 'No KitchConfig, '; } if(isset($_POST["designer$upd_KitchConfigID"])) { $upd_KitchConfigDesigner = $_POST["designer_$upd_KitchConfigID"]; } else { $upd_KitchConfigDesigner = 1; $ErrMsg = $ErrMsg . 'No Designer, '; } echo("designer_$upd_KitchConfigID: ".$_POST["designer_$upd_KitchConfigID"]."<br><br>");
I created a drop-down menu using a MySQL statement in php for a form. My drop down menu works fine, but I want to assign a default value to it (normal text) the value will never change, thus I do not need to extract the default value from the table, I already know the value. Here is the basic snippet from the script: <?php include("../includes/xxx.php"); $cxn = mysqli_connect($host,$user,$password,$dbname); $query = "SELECT DISTINCT `plant_id` FROM `plant` ORDER BY `plant_id`"; $result = mysqli_query($cxn,$query); while($row = mysqli_fetch_assoc($result)) { extract($row); echo "<option value='$plant_id'>$plant_id</option>\n"; } ?> I want to make a table for each paddler_id (Field) which exists into pushup Database My code for paddler_id = 1 is require "../sql.php"; $result = mysql_query("EXPLAIN pushup"); $r = mysql_query("SELECT * FROM paddlerinfo t1 LEFT JOIN pushup t2 on t2.paddler_id=t1.id LEFT JOIN practicedate t3 on t3.practice=t2.practice_id ORDER BY t1.firstname ASC "); $r1 = mysql_query("SELECT * FROM pushup where paddler_id =1 ORDER BY practice_id ASC "); echo "<table width='30%' border='1' cellpadding='0' cellspacing='0' style='font-family: monospace'>"; echo "<tr>"; echo "<td>DATE</td>"; while ($row = mysql_fetch_array($result)) { if (in_array($row["Field"], array("paddler_id", "practice_id", "p_id"))) continue; echo "<td>",($row["Field"]), "</td>"; } echo "</tr>"; while (($data = mysql_fetch_array($r1, MYSQL_ASSOC)) !== FALSE) { unset($data["p_id"],$data["paddler_id"]); echo "<tr>"; foreach ($data as $k => $v) { echo "<td>"; echo"$v"; echo "</td>"; } echo "</tr>"; } echo "</table>"; mysql_free_result($result); mysql_free_result($r); mysql_free_result($r1); mysql_close(); The problem is on line $r1 = mysql_query("SELECT * FROM pushup where paddler_id =1 ORDER BY practice_id ASC "); I want to put something which makes it paddler_id = X where x = 2,3,4,5... and x exists in database and do not print twice the x (because that database may have rows where x = same id How do i do that?? Or something like that... I am not sure how to put this.. Anyway, I'll just get started with explaining my problem. I have an admin-page in which you can delete the comments given on blogs, using checkboxes and clicking on a button with the value 'verwijderenSubmit'. The deletion part works just fine, nothing wrong. However, I also want to be able to EDIT the comments with an other button called 'bewerkenSubmit', using the same checkboxes that I use for deletion. Selecting the right CID (CommentID) is no problem, because that works the same as the deletion-part, but selecting the right textarea to update into the database is the problem... I uploaded a file here with the whole code: http://dhost.info/ddfs/myproblem.html I escaped the textarea within with square brackets, because otherwise the whole textarea would screw up.. I also added <!-- RELEVANT CODE --> to select the parts that I need to change. Well, I hope you understand my problem and can help. |