Another question which has me perplexed:
I have a table which enables users to enter as many rows as they like based on their userid and unique id (auto incremental).
I need to be able to get this information from mysql and place the previously entered information into the fields on the web application (they may need to be edited before confirming that they're correct).
I store the total number of records for that user so far in one variable, and the total number of records for all users in another variable.
The question is: how do I get the range of ids for the records the user has already enterered.
Example: User 1 has 2 records in the database and there is 7 in total (5 by another user). How would I get the unique IDs of the 2 records that already exist?
Thanks for any suggestions you may have!
I'm not entirely sure what you mean, so this may or may not be helpful.
This SQL should give you the record ids:
SELECT id FROM tableofuserrows WHERE userid = [User Id]
You can then fetch this from the database with PHP, e.g.
$q = mysql_query('SELECT id FROM tableofuserrows WHERE userid = ' . (int) $_GET['userid']) or die(mysql_error());
$result = array();
while ($row = mysql_fetch_assoc($q)) {
$result[] = $row['id'];
}
mysql_free_result($q);
echo json_encode($result);
So if you wanted to fetch these IDs from the browser using jQuery:
$.getJSON("http://url", { userid: 3 }, //set userid properly
function(data){
$.each(data, function(i,id){
//do something with the recordid
alert(id);
});
}
);
Do you have to do this dynamically using jquery or can you load the fields in the web form with the rest of the page using php ?
Either way, you're going to need to query the database table for all rows where userid = a certain user. Once you get these results, you'll need to create a page you can call and get results from using jquery if you're going that route.
Someone just posted what I'm saying with code examples :-)
I decided to use MIN(id) in the select statement, counting how many rows there are and then populating the form fields accordingly, starting with the min value and adding the counted rows. Works well ;)
Related
This is a rough example of my mysql query (note: this is inside an other loop that goes through all users):
$query = db.query('SELECT * FROM table WHERE userid = $uid AND reminded = 0');
while ($row = $query->fetch()) {
// send personalized reminder email to the user
db.query('UPDATE table SET reminded = 1 WHERE userid = $uid');
}
The field reminded is set to 1 for all instances for that user.
My question is:
Is the query/while (fetch) already loaded into memory based on the original terms (reminded = 0), or will the remaining while loop behave according to those updates (reminded = 1)?
Let's say the user had 50 rows where reminded is 0, and the query selects those: Are they still existing with the value 0 in the rest of the while loop even though they were all changed to 1 during the loop?
Assuming that the code and SQL you have is only an example (because you should update directly without a php loop).
The fetch on the table rows is executed on the DB row by row.
So, if one or more of these rows are updated in the while loop, in next iterations you will retrive and update (again) the previous updated rows.
I think that you have to be careful "only" if you are updating a field that is part of an index or a field that is used in the SQL to retrieve data (es. a field used in the ORDER BY, etc.).
I want a straightforward answer with an example (NO LINKS please) to see how I can retrieve a specific person's last name from a table in a MySQL database using PHP and save it into a variable (i.e. $_Session). I have been looking for this question and I don't get anything related to one row in PHP. If this can be done better with mysqli* functions then I would be glad to see it.
Example
$getData = "SELECT lastname FROM person WHERE name='$name'";
$getData_q = mysql_query($getData) or die('Error');
Then i want something like this:
$_SESSION['lastame']=$getData_q; <- Please correct me,
I'm not asking to get a lastname from an input, I'm asking to get it from the table person in the database with the SELECT.
Use
$getData_q = mysqli_fetch_object($getData_q);
$_SESSION['lastame']=$getData_q->lastame;
But ensure that that num rows is greater than 0 and data would return a single row.
I want to be able to bring back the earliest logon time per user, so only 1 record (the earliest record) displays for each user
I've tried various ways of GROUP BY but can't seem to get it quite right (if that is actually the correct way of doing). username is the unique value which can be used to GROUP BY
Here's the code I'm currently working with..
SELECT username, name, logon, added FROM data WHERE (date(added) LIKE '$date') AND (logon = (SELECT MIN(logon) FROM data))
I've also tried (below) but only get one result back, only displaying one user
WHERE (date(added) LIKE '$date') AND logon = (SELECT MIN(logon) FROM data)
The first image is what I'm currently getting, the second image is how I want my results to display, please see below
Let me know if you require anymore information, I've tried to put as much as possible
Thanks,
Tom
You are close. Your query needs a correlation clause:
SELECT d.*
FROM data d
WHERE date(d.added) = '$date' AND
d.logon = (SELECT MIN(d2.logon) FROM data d2 WHERE d2.name = d.name);
Note: The logic for added is confusing. First, you should not use like with dates. And, for that matter, you should not be inserting parameter values into the string, you should be using query parameters. And, actually, I don't see the need for that column; your question doesn't mention added.
use this query , problem will be solved
SELECT username, min(logontime) FROM data where date(logontime) = '2016-08-10' group by username
do this:
<?php
$users = array();
$sql = "select * from users";
$result= mysqli_query($conn,$sql);//$conn is your connection object
while($user = mysqli_fetch_assoc($result)){
if(!in_array($user['name'],$users)){
$users[$user['name']]=$user['logOnTime'];//replace key names with your table row names
}
}
//$users is an array that has your user names as key and their last logon time as value
?>
I want to create a PHP page which selects a random record from MySQL database (a string, which will be used as a unique "token"). I want to select this random record only once and never again afterwards.
In order to do so, I add an extra field to the table (named 'numberfield', containing number 0), which is incremented at the moment the specific record has been selected. This way, only records with the value of 0 in the numberfield table field can be selected. As soon as the random record has been selected the numberfield field is incremented to 1 and can not be selected anymore. I'm thinking about using the following PHP code:
$result = mysql_query("SELECT token FROM table WHERE numberfield < **1** ORDER BY RAND() LIMIT 0,1");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0];
mysql_query("UPDATE table SET numberfield=numberfield+1 WHERE token=" + $row[0] + "");
Will this be the right way to do it ? Any thoughts ?
Furthermore, I want to avoid a different random record is selected at page refresh. What will be the right and most simple way to keep the "token" in cache ? For example, is it possible to keep the "token" in a session which will not be overwritten during page refresh, or do I have to use other techniques like Ajax etc. Your help and comment is highly appreciated !
You should stop using mysql_ functions as they are deprecated.
You should avoid using ORDER BY RAND() in larger tables because of overhead incurred from seeking a random number.
To accomplish a SELECT ... UPDATE you would need some sort of locking. There is a slim chance that a row could be randomly selected twice. This can be prevented using a stored procedure.
You can just use the session id generated by PHP or a part of it. This topic talks about how unique a session id is and this topic discusses the varying lengths.
You can alternatively create a random string on the PHP side which would save overhead from connecting to the database.
The current site for which I'm re-designing and developing is http://www.gdi-brighton.co.uk/. Most of the changes are cosmetic, and I've stripped the nav down to 3 links: GDI-Brighton (home page), Profiles and News. The site uses a custom CMS built in PHP from a previous student.
When visiting the home page I'd like for a random student profile page to load. There is an id and name_url for each student, which you can see when clicking on one of the thumbnails for a student on the current site.
I'm familiar with Math.floor(Math.random()) but have no idea where to start concerning this.
Please let me know if you need any more information. Thanks for your help.
Ryan
If you are using a relational database and the ids of the student entities are following a sequence (e.g. increasing by 1 etc.), then you can get the current sequence number with a single simple query to your database (you can google for nextval() of a sequence on the web). Assign this number to a variable and use it as an upper limit when you are generating a random student id. To handle the cases where the generated random number doesn't correspond a valid student id, (i.e. some of the students might have been deleted from the database.), you can just use a while loop that contains the random id generation code but exists on a valid id generation. After that, just query the database with this valid random id and fetch the url of the profile of the corresponding student.
You can do this in your PHP. Here is the concept (not actual working code):
$result = mysql_fetch_row(mysql_query("SELECT MIN(id), MAX(id) FROM table"));
$min = $result[0]; $max = $result[1];
$id_to_retrieve = rand($min, $max);
$random_student = mysql_query("SELECT * FROM table WHERE id = {$id_to_retrieve} LIMIT 1");
Note that this does not check whether the record with that ID exists in the last query. If it doesn't exist you can get another random ID or get the closest ID that does exist.
After all this is done you output the random student card and retrieve the result with jQuery (with load() or something--you don't need to pass any variables to PHP for this).
You can pick a random url on the client-side, too with this code:
var url = $('li.illustration:eq('
+ Math.floor($('li.illustration').length * Math.random())
+')>a').attr('href')
But it feels too hackish and the server seems the best place to do it.
You could use something like this??
var randomnumber = Math.floor(Math.random() * 3);
if (randomnumber == 0) { DisplayProfile(0); }
if (randomnumber == 1) { DisplayProfile(1); }
if (randomnumber == 2) { DisplayProfile(2); }
DisplayProfile would contain your JQuery code that would organise your page to display the right info based on the information passed (in my example 0, 1 or 2)