PHP (and SQL) how to get given record - php

I have Data base "players" with:
id Name gold
1 joe 50
2 tom 40
3 jzd 70
I use a PHP to get info from base to variable:
$base = $connection->query("SELECT * FROM Players");
$data = $base->fetch_assoc();
When i use
$data['name'];
I get only a name FIRST id, how to get name for example id 2 or 3?

If you want to return the record for a specific user use
SELECT * FROM players WHERE id = <id>;
If you want to list all the players returned from your first query (select all, no where statement), you need to loop through the array returned from doing your query. Use a foreach (here are some examples

Related

SELECT query is only SELECTING/CHECKING the first row, how do I SELECT/CHECK all

I have this simple query:
$q5 = "select listingid FROM userlisting WHERE userid = '$_SESSION[UserID]'";
$r5 = mysql_query($q5) or die(mysql_error());
$a5 = mysql_fetch_array($r5);
The userlisting table is a many to many relationship. It is used as a lookup table. Each userid can be associated with multiple listingids and vice versa.
Also in my file (a html template file) I have this code
if(!empty($_SESSION[UserID]) and $a5['listingid'] == $_GET['id']) :
So I am wanting to check if the listingid column in userlisting table = the id of the page (well, it is a property website and it is the id of the property). As each user can be associated with many listingids I need to be able to check multiple rows. But for some reason it only checks the very first row.
In the userlisting table there is the following test entries:
userid | listingid
1 1
1 2
So one user associated to two listingids. However, it is acting like this userid is only associated with listingid 1, the very first row.
You are only grabbing the first entry.
$a5 = mysql_fetch_array($r5);
This does not fetch the whole query result, but only the first row. If there is none, it will return false.
You have to create a loop to get more results.

Display random records in each page but not the same

Well guys i have this query
$mysql = "select * from xxx where active = 1 order by Rand() limit $start,12";
mysql_query($mysql);
Everything works great so far.
I want: when i am pressing the next button (page 2 or three etc) to see the next 12 random records but do not display the first 12 random records that i had in my previus page!
Thank you all!
p.s Sorry guys for my bad english!
Just try to retrieve the data you need in an array, randomize it with shuffle() in PHP, and paginate the result with some JQuery, it will be awesome, just one query and no refresh. ;)
You need to keep one array (e.g $arrRecordIds) to track all the id's of records shown on previous pages.
When you are on first page:
$arrRecordIds=array(); // Empty array
When you are on second page:
$arrRecordIds=array_merge($arrRecordIds, $arrNewRecordIds);array_unique( $arrRecordIds );
If your select query simply concat- where id NOT IN ( implode(',', $arrRecordIds ) )
Here $arrNewRecordIds should contains id's of the records on the page.
You can keep track of the previously shown records' ids and put them in an array.
In your query use id NOT IN (array)
Apply the concept of Systematic Random Sampling,
Number the records N, decide on the n (pagination size, eg: 10, 20)
(sample size) that you want or need k = N/n = the interval size
Randomly select an integer between 1 to k then take every k th unit
Refer: http://www.socialresearchmethods.net/kb/sampprob.php
Try using the following script in your showdata.php file
$per_page = 12;
$sqlc = "show columns from coupons";
$rsdc = mysql_query($sqlc);
$cols = mysql_num_rows($rsdc);
$page = $_REQUEST['page'];
$start = ($page-1)*12;
$N = 1000; //Total rows in your table (query to get it dynamically)
$n = $per_page;
$k = ceil($N/$n);
$range[] = $page;
for($i=1;$i<$n;$i++) {
$range[] = ($page+$k)*$i;
}
$sqln = "SELECT * FROM ( SELECT #rownum:= #rownum+1 AS rindex, n.* FROM xxx n, (SELECT #rownum := 0) r ) AS rows WHERE rindex IN (".implode(',',$range).")";
$rsd = mysql_query($sqln);
SOLUTION - that works a treat.
do a select random search of all required records
generate a random user-id eg. "smith".rand(1000,10000)
form a string of all random keys upto required no of records per page
insert above in a table/field containing a corresponding page no.
repeat/loop above until no more pages/recs remaining - use array_splice(str,from,to) - then use $notscreen = print_r($splice, true) for string storage to table -> randompages:
tb.rec-no | user-id | pageno | string ( with keys of recs upto recs/page)
122 | aj7894 | p1 | [0]=>100[1]=>400[2]=>056[3]=>129
123 | aj7894 | p2 | [x]99=>[x]240=>[x]7895[x]458=>320
... upto whole array of pages /no of records / all pages - no duplication of data - only 1-column of key of recs stored in random as retrieved
use user-id & pageno with WHERE to pull out random keys for that individual user & page
convert string back to array and pull out matching key recs for specific pages using the array in a SELECT WHERE query with implode
re-circ [ user-id & pageno ] using $_GET/POST for duration of search/view - reinitialise when new view or new search commences
notes:
-better to use list for search - but requires more work to format string - should give random page results as originally stored
problem with array matching is it orders records per page; lowest being first - not so random for the page display
temp table no good - because cannot be accessed when script is thrown back to server for 2nd and more time - it's lost from memory by mysql
php rules - no flimsy cookies or java-script !
BIG PROBLEM - SOLVED.
re-compsense for help received from your posts / answers.
Happy Days!

PHP + SQL : Loop in php to get multiple WHERE conditions

So lets say I have a list with some entries(ids) of a table. I want to get the table rows which have the exact ids as in the list. How could I formulate this in php with sql statements.
i.e
idList = [23,43,65,234,54];
SELECT *
FROM TABLE
WHERE id = 23
AND id = 43
AND id = 65
AND id = 234
AND id = 54;
Sorry, the AND was a mistake.
$list='23,43,65,234,54';
$SQL='SELECT * FROM TABLE WHERE id in ('.$list.')';
Instead of checking each id, you can use the IN operator to search in a set of values:
SELECT * FROM kittens WHERE id IN (23,43,65,234,54)
Your search is bound to return no rows as the id cannot have more than one value at a time.
I'm guessing you want to return rows where idmatches either of the values in which case you can
1) Use the OR operator in place of AND
2) Or better use the IN operator

php simple following-follower system, removing a value from array and updating with foreach (updating doesn't work)

I made a simple following-follower system with php(pdo) and mysql. My problem is,
Let's say there is a user name Mike with ID number 99. And Mike has two followers, Greg(id = 77) and Jenny(id = 88)
Greg's following list looks like this (1,2,3,4,99), and Jenny's following list looks like this (5,6,99,7)
What I am trying to do is, when Mike(99) deletes his account, I want to remove id number 99 from Greg(77) and Jenny(88)'s following lists.
Table called 'mytable' has 3 fields. id(INT), following_list(text), follower_list(text).
I've been struggling with this problem for a few days. Can anyone please give me some advice? Thank you so much in advance!!!
Below is my update function
public function update_following_list(){
// $this->myid is Mike's id number(99) who is about to delete his account
// Selecting the list of people following Mike
$query = "SELECT 'follower_list' FROM 'mytable' WHERE 'id' = $this->myid";
$result = $this->dbc->query($query);
foreach($result as $row){
$this->follower_list = $row['follower_list'];
// When I echo $this->follower_list, I get 77,88
// Now querying Greg(77) and Jenny(88)'s following_lists, which have Mike's id number(99) in them.
$query = "SELECT 'following_list' FROM 'mytable' WHERE 'id' IN ($this->follower_list)";
$result = $this->dbc->query($query);
foreach($result as $row){
$this->following_list = $row['following_list'];
// When I echo $this->following_list, I get both Greg(1,2,3,4,99) and Jenny(5,6,99,7)'s following lists
// Here, I am turning following list into array by using explode
$this->following_array = explode(",", $this->following_list);
foreach($this->following_array as $key => $value){
if($value == $this->myid){
// Removing Mike(99)'s id number from Greg and Jenny's following lists
unset($this->following_array[$key]);
// Add back commas, which will then become string
$this->new_following_list = implode(",", $this->_following_array);
// When I echo $this->new_following_list, I get both Greg(1,2,3,4) and Jenny(5,6,7)'s new list without Mike(99)'s id number
// My problem starts here. I was able to remove Mike's id number from Greg and Jenny's lists. But I am having a trouble updating Greg and Jenny's following lists with new following lists.
// The update query below does not work...
$query = "UPDATE 'mytable' SET 'following_list' = $this->new_following_list WHERE 'id' IN ($this->follower_list)";
$result = $this->dbc->query($query);
} // End of if($value == $this->myid)
} // End of foreach($this->following_array as $key => $value)
}
}
} // End of function
This will not scale properly. It's better to normalize your data model like this:
following
user_id | following_user_id
---------------------------
77 | 1
77 | 2
77 | 3
77 | 4
77 | 99
88 | 5
88 | 6
88 | 7
88 | 99
And add two indexes:
UNIQUE(user_id, following_user_id)
INDEX(following_user_id)
To get followers of 99:
SELECT * FROM following WHERE following_user_id=99;
To see who 77 follows:
SELECT * FROM following WHERE user_id=77;
I think your database setup is not optimal. Store comma-separated values in one field, screams for a binding table and some normalization !!
You should have your comma separated value list to be a table/relation, e.g.:
followTable:/ user_id | follows
Deletion of mike's id is then as simple as:
DELETE FROM followTable WHERE follows = 99 OR user_id = 99
The latter makes sure the links between Mike and his followers are being deleted also.

MySQL: Join (2 tables) vs single queries (1 table)

In PHP, I have an array of 11 persons where just the ID of each person is given:
$persons = array(1, 3, 39, 72, 17, 20, 102, 99, 77, 2, 982);
In my MySQL database, there's a table containing detailed information about each person:
TABLE personInfo
- ID (integer)
- name (string)
- birth date (timestamp)
- weight (decimal)
- ...
PROBLEM:
So now, I want to select the matching name for each ID in the PHP array. I can only imagine two solutions to do this:
1. for-loop:
foreach ($persons as $person) {
$result = mysql_query("SELECT name FROM personInfo WHERE id = ".$person);
}
2. logical operator OR
$result = mysql_query("SELECT name FROM personInfo WHERE id = 1 OR id = 3 OR id = 39 OR ...");
Both solutions are slow, aren't they?
But if I had another MySQL table containing the IDs of the PHP array ...
TABLE ids
- ID (integer)
... I could use a join to make a really fast MySQL query, right?
$result = mysql_query("SELECT a.ID, b.name FROM ids AS a JOIN personInfo AS b ON a.ID = b.ID");
QUESTION:
Is all this correct so far? If yes: Why is this so? The MySQL query is faster if I have a second table? With only one table it is incredibly slow? What is the fastest way to solve my problem (selecting the names matching the IDs of the PHP array)?
If you have lots of ids (several hundreds or more), feeding the values into a temporary table and joining it is actually faster.
You may want to read this article:
Passing parameters in MySQL: IN list vs. temporary table
IF you have ID's you should just query the Id's you have. So
$result = mysql_query("SELECT name FROM personInfo WHERE id = 1 OR id = 3 OR id = 39 OR ...");
would be right, although I would use
$result = mysql_query("SELECT name FROM personInfo WHERE id IN (1,2,3,4....) )

Categories