PHP - Select Specific Mysql Rows
So I have an array of IDs that I would only like to select from a database table instead of everything in the table.
How might I go about doing that? Similar TutorialsI have 2 queries that I want to join together to make one row
How can i select the last 3 rows in a table and order it by ASC. When i use DESC it displays the results in the wrong order. $query24 = mysql_query("SELECT * FROM notifications WHERE to_id='$session' AND state='1' ORDER BY id DESC LIMIT 3 "); Hello. I'm a newbie so sorry if this isn't the best forum to post my problem.
I am using a MySQL and PHP to create a web app. I have authentication, and I can register users. I also have a form that users provide information and it is successfully inserting data into a table in my database.
I will use fictional fields for my database table called meal_info:
username
dateStartedDiet
numberMealsPerDay
costPerMeal
Problem: Select user-specific data from the MySQL database, using Session username to select only the current user's data, then display it and do some calculations.
Here is thecode at the top, and I am fairly sure it's working:
session_start(); //execute commone code
require("common.php"); //includes code to connect to database, etc.
if(empty($_SESSION['user'])) I am building a commenting system, it's sort of like facebooks comments. I have it right now so it loads the first last 3 comments in the database, and then there's a button to view all comments. I have it working fine, except when you add another comment to it, and then click the view all comments, This is the script that loads onload showing the last 3 comments $limit = 3; $query5 = mysql_query("SELECT * FROM sub_comments WHERE status_id='$id' ORDER BY id DESC LIMIT $limit"); This is the php script that runs when you click view more //($start_id would be 3 in this case) $query5 = mysql_query("SELECT * FROM sub_comments WHERE status_id='$comment_id' ORDER BY id DESC LIMIT $start_id, 1000"); so to try to show you what's happening: OnLoad--------------------------------|---When you add more comments, (let's just say u add 1 comment before u click view comments)---- comment 9 --------------------------| comment 10 comment 8 --------------------------| comment 9 comment 7 --------------------------| comment 8 ------------------------------------------| comment 7 ----to be loaded onclick-------------|------What's loaded onclick--- comment 6 --------------------------| comment 7 comment 5 --------------------------| comment 6 comment 4 --------------------------| comment 5 comment 3 --------------------------| comment 4 comment 2 --------------------------| comment 3 comment 1 --------------------------| comment 2 ------------------------------------------| comment 1 (see how "comment 7" is being shown twice in a row) I've a simple Inset List (jQuery Mobile) of several items with a Flip switch, Drop down, check box and Slider elements. I have wrapped this Inset List inside a HTML Form. <code> <div data-role="fieldcontain"> <ul data-role="listview" data-inset="true"> <li data-role="list-divider"> Inhouse capabilities </li> <li> <label for="flip-b">Project Manager</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li> <label for="flip-b">Site Supervisor</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Architect</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Builderworks</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Electrical</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Mechanical</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Hydraulics</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Joinery</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li> <label for="select-choice-1" class="select">Main Location:</label> <select name="select-choice-1" id="select-choice-1"> <option value="NSW">NSW</option> <option value="ACT">ACT</option> <option value="VIC">VIC</option> <option value="SA">SA</option> <option value="QLD">QLD</option> <option value="NT">NT</option> <option value="WA">WA</option> <option value="TAS">TAS</option> </select> </li> <!-- Select Menus: Main Location--> <li> <div data-role="fieldcontain"> <fieldset data-role="controlgroup"> <legend>CBA Reference</legend> <input type="checkbox" name="checkbox-1a" id="checkbox-1a" class="custom" /> <label for="checkbox-1a">Commercial</label> <input type="checkbox" name="checkbox-2a" id="checkbox-2a" class="custom" /> <label for="checkbox-2a">Retail</label> </fieldset> </div> </li> </ul> </div> <!-- End of Field Contain div tag --> <a href="#additionalinfo" data-role="button" data-inline="true" data-iconpos="left" data-theme="b">Additional Info</a> <a href="./search2.html" rel="external" data-ajax="false" data-role="button" data-inline="true" data-icon="search" data-iconpos="left" data-theme="e">Search</a> </code> I want to know, how I can include only the elements the user selected in my SQL query. Lets say, User wants to find the Electrical workers in QLD, then he will select Yes for Electrical and QLD as Main Location and the other items he would not touch. Now, how can I include only those two values in the select clause. Say, Select Electrical, Main Location from table where Main location='QLD'. I used POST method to gather users input. I use PHP, MySQL for this project. Any ideas on how to achieve this. Regards Sandeep Assuming I have a result object: $result = mysqli_query($sql_string); How can I get specific rows, i.e. multiple rows are returned 8 total, but I was rows 2-6. Thanks. I have a simple database set up for story awards given out by different groups. Here are some of the fields I'm using: Author Title Year Summary Some of the rows are nearly identical with the same Author and Title, but sometimes a different year or or others have a Summary for the story where otherwise it would be empty for a different row. The problem I'm having is I want to fetch the summary of the story from all rows where the Author and Title are identical. Currently the code is fetching a random row with the same Author and Title, but won't show the Summary if that specific row doesn't have the summary filled in (and where other rows of nearly identical information would have the summary). Here's an example of nearly identical rows: 'Boring Title', 'Boring Author', '', '2012' 'Boring Title', 'Boring Author', 'Boring Summary', '2012' How would I go about fetching all rows with the identical Author and Title and then showing the Summary even if only one of those rows has information in the Summary field? Much obliged for any help. Here's the code I'm working with: Code: [Select] <?php mysql_connect(localhost,db_user,pw); @mysql_select_db(db_database) or die( "Unable to select database"); $quer="SELECT * FROM archives ORDER BY RAND() DESC LIMIT 1"; $re = mysql_query($quer); while ($ro = mysql_fetch_array($re)) { extract($ro); $please = ''; if (strlen($ro[summary]) == 0) { $please = "The summary is empty. Please help the Archives by <a href=\"edit.php?cmd=edit&author=$author&title=$title\">filling out the summary</a>."; } $select_author = mysql_query("SELECT DISTINCT author FROM archives WHERE `title` = '" . mysql_real_escape_string($title) . "' ") or die (mysql_error()); $aut = ""; while ($row2 = mysql_fetch_array($select_author)) { $aut .= "<a href=\"author.php?author={$row2[author]}\">$row2[author]</a> & "; } $aut = substr($aut,0,-3); echo '<div style="margin: 5px;"> '.$summary.''.$please.' <p style="float: right; width: 100%; margin-top: 10px; text-align: right;"><i> ~ <a href="info.php?author='.$author.'&title='.$title.'">'.$title.'</a> by <a href="author.php?author='.$author.'">'.$aut.'</a></i> </div>'; } ?> what Im basically trying to do is just like a phpmyadmin function... you select rows you want to update with a checkbox and then it takes you to a page where the rows that are clicked are shown in forms so that you can view and edit info in them... and then have 1 submit button to update them all at once. Hi guys, I am getting data from a json source: ``` $jsondata = file_get_contents($url);$response = json_decode($jsondata, true) echo "<pre>"; print_r(array_keys($response));; echo "</pre>"; ``` and this returns: ``` Array ( [0] => jsonapi [1] => data [2] => links ) ``` I want to extract data from specific key in the data array (eg 'title'): ``` [data] => Array ( [0] => Array ( [type] => recipes [id] => d6cd7643-6e44-4d26-9ed9-9da7196cef12 [attributes] => Array ( [internalId] => 7 [isPublished] => 1 [title] => Deep mediterranean quiche [createdAt] => 2019-05-07T13:34:27+0200 [updatedAt] => 2019-05-07T13:34:27+0200 [isPromoted] => 1 [path] => /recipes/deep-mediterranean-quiche [cookingTime] => 30 [difficulty] => medium [ingredients] => Array ( [0] => For the pastry: [1] => 280g plain flour [2] => 140g butter [3] => Cold water [4] => For the filling: [5] => 1 onion [6] => 2 garlic cloves [7] => Half a courgette [8] => 450ml soya milk [9] => 500g grated parmesan [10] => 2 eggs [11] => 200g sun dried tomatoes [12] => 100g feta ) [numberOfservings] => 8 [preparationTime] => 40 [instructions] => ``` How do I loop through the data array and select just the 'title' and 'difficulty' for example? Edited May 12, 2019 by ludo1960hello, im only getting the second half of my results showing in my dropdown box. here is my code. Code: [Select] if(isset($_GET['id'])) { $uid = $_GET['id']; } $forward = mysql_query("SELECT * FROM players WHERE status = '1' AND position = 'forward' ORDER BY name"); $forward1=""; while($row1 = mysql_fetch_array($forward)) { $forwardid=$row1["id"]; $forwardname=$row1["name"]; $forwardteam=$row1["team"]; $forward1.="<OPTION TITLE=\"$forwardteam\" VALUE=\"$forwardid\">".$forwardname.'</option>'; } $result = mysql_query("SELECT * FROM picks WHERE uid = '$uid' AND pickid = 'forward1'"); while($row = mysql_fetch_array($result)) { $playerid=$row['playerid']; } if(isset($forwardpick1)) { $result1 = mysql_query("SELECT * FROM players WHERE id = '$playerid'"); while($row1 = mysql_fetch_array($result1)) { $forwardpick1=$row1['name']; } $forwardpick1="<br /><br /><font color ='#000000' size = '5'><b>$forwardpick1"; } else { $forwardpick1=" <form method='POST' action='draftpick.php' name='forward1'> <p><font color='#000000'><select size='1' name='player'> <?php echo '$forward1'; ?> </select><br><br><input type='submit' value='Submit' name='submit'></font></p> </form> "; } any direction is appreciated. $result = mysql_query("SELECT * FROM `friend_system` WHERE `friend_system_accepter` = '$myusername' "); echo mysql_num_rows($result);This displays the total rows in the table. $result = mysql_query("SELECT COUNT(friend_system_accepter) FROM `friend_system` WHERE `friend_system_accepter` = '$myusername' "); echo mysql_num_rows($result);This displays '1', which is incorrect. I want to echo out the number of rows where 'friend_system_accepter' = $myusername Thanks 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, I have the project where i want to get the structure like tree. My table structu Section_Id Section_Parent Section_Name 1 0 America 2 0 China 3 1 New york 4 1 Washington 5 2 Buffalo How to retrieve the records.. I need a structure like this in a select button: America New york Buffalo Thanks, Hi, All: I'm trying to figure out what way it's the best way to pull info belonging to a specific user based on whether he's a logged-in "member", and want to make sure he's not able to access any other member's details... would the best way be to try to match the user's "username" stored in a $_SESSION when fetching his info, something like this: Code: [Select] <?php // Assume the login combo is this: $username = $_POST['username']; $password = $_POST['password']; // Assume he has already logged in: $_SESSION['username'] = $username; //EXAMPLE 1: SELECTING user info simply from actual DB username/password match: if ($_SESSION['username']) { $userRecords = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'"); $userInfo = mysql_fetch_array($userRecords); echo $userInfo['id'] . $userInfo['username'] . $userInfo['first-name'] . $userInfo['last-name'] . $userInfo['date-register']; } // EXAMPLE 2: or SELECTING user info based on $_SESSION['username'] value: if ($_SESSION['username']) { $userRecords = mysql_query("SELECT * FROM users WHERE username = . $_SESSION['username'] . AND password = '$password'"); $userInfo = mysql_fetch_array($userRecords); echo $userInfo['id'] . $userInfo['username'] . $userInfo['first-name'] . $userInfo['last-name'] . $userInfo['date-register']; } ?> So, my question is, are this actually working differently? is one better than the other as far as security, preventing other users from hacking either on purpose or accidenally into other user's details? thank! Appreciate any feedback... 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>"; ?> im wondering how to get php to read the latest row (instead of show them all) and when another one comes it replaces it once the page refreshes I am trying to get specific data from a MySQL table but cannot seem to find a proper command. Code: [Select] $link = mysqli_connect('#####', '########', '########'); $user = $_SESSION['username']; $email = mysqli_query($link,"select email from members where username='$user'"); echo $email; Specifically, I am trying to get the email address stored for the user specified by the session, and display that address. However, I do not get any output with the current code, and am not sure what to try next. I have tried mysqli_fetch_row() but it only returns an error. Hi guys, How do I call the 2nd row of 'TSuperQuestion'? Code: [Select] <?PHP $con = mysql_connect("localhost","ph6theo", "xxxx"); if (!$con) { die('Could not connect: ' . mysql_error("oop")); } mysql_select_db("ph6theo_testDB") or die(mysql_error()); $result = mysql_query("SELECT * FROM QANDATable "); $row = mysql_fetch_array($result); echo $row['TSuperQuestion']; ?> |