PHP MySQL with two query - php

I need to do a SELECT * FROM table_X , the problem is table_X is the result of another query, I don't know how to do it, perhaps with two loop, something like this :
<?php
$query1 = mysql_query("SELECT * FROM table_ref");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query(" SELECT * FROM '$name' ");
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
?>
The tables are all similar & I can't do joint there's no keys. So what I want is to show only the results of the second query from each results of the first query !

So, what's your structure? I don't understand. You have column table_name where are listed a lot of tables? If so, just use backquotes on your $name:
$query2 = mysql_query(" SELECT * FROM `$name` ");

Apart from the obvious that has been pointed out in the comments, you're overwriting $row in the second loop.
Also, you're trying to read an array ($data) that is not defined.
The following will work much better (but still isn't ideal):
$query1 = mysql_query("SELECT `table_name` FROM `table_ref`");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query("SELECT `itime` FROM `$name`");
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}

just change your quotes to have the query ready to be started
change
$query2 = mysql_query(" SELECT * FROM '$name' ");
to
$query2 = mysql_query(" SELECT * FROM `".$name."` ");
i would also rather sugest to check this part
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
you already used variable $row to fetching previus query so better to change to something else, look like $data is matching your needs because you already used but you did not declare it
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}

Try this query:
select x.* from ( SELECT table_name FROM table_ref) as x

Related

Predefined counter not updating in select statement

Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";

Display single column value of mysqli query

How can I get a single column value from mysqli? The result should be single row with only one column.
This is what I have tried:
$query = "SELECT MAX(`userid`) FROM `user`";
$rlt = mysqli_query($this->db, $query);
echo $rlt['userid'];
You are not fetching the row after executing the query:
$query = "SELECT MAX(`userid`) FROM `user'";
$rlt = mysqli_query($this->db,$query);
$row = mysqli_fetch_row($this->db, $rlt);
echo $row[0];
The alternative would be to use an alias for the computed field and use fetch_assoc:
$query = "SELECT MAX(`userid`) as `maxid` FROM `user'";
$rlt = mysqli_query($this->db,$query);
$row = mysqli_fetch_assoc($this->db, $rlt);
echo $row['maxid'];
try with create alias and fetch result after query execution also your quote of user' looking wrong
$query = "SELECT MAX(`userid`) as userid FROM `user`";
$rlt = mysqli_query($this->db,$query);
$r = mysqli_fetch_assoc($rlt);
echo $r['userid'];
or fetch only one row like:-
$r = mysqli_fetch_row($this->db, $rlt);
echo $r[0];
You should create alias here.
Use this one:
$query = "SELECT MAX(`userid`) as Max_Userid FROM `user'";
$rlt = mysqli_query($this->db,$query);
$row = mysqli_fetch_assoc($this->db, $rlt);
echo $row['Max_Userid'];
Note: Always use alias when you use mysql function in query with fields.

How can I add array values to a MySQL query?

I'm using the following code to sort MySQL queries into time/date:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row = mysql_fetch_array($result))
{
print($row['user']);
}
instead of having the PHP run through and show all the values in the table can I have it show the values from an array?
So, you want to find specific users in the SQL query to return? Build your query programmatically:
$users = array('User1','John','Pete Allport','etc');
$sql = "SELECT * FROM `users_newest_post` WHERE ";
$i = 1;
foreach($users as $user)
{
$sql .= "`username` = '$user'";
if($i != count($users))
{
$sql .= " OR ";
}
$i++;
}
$sql .= " ORDER BY `users_date_post` DESC";
$result = mysql_query($sql);
Which would get you a query like:
SELECT * FROM `users_newest_post`
WHERE `username` = 'User1'
OR `username` = 'John'
OR `username` = 'Pete Allport'
OR `username` = 'etc'
ORDER BY `users_date_post`
DESC
So, you want to find all posts for a certain date or between two dates, kinda hard to do it without knowing the table structure, but you'd do it with something like this:
//Here's how to find all posts for a single date for all users
$date = date('Y-m-d',$timestamp);
//You'd pull the timestamp/date in from a form on another page or where ever
//Like a calendar with links on the days which have posts and pass the day
//selected through $_GET like page.php?date=1302115769
//timestamps are in UNIX timestamp format, such as you'd get from time() or strtotime()
//Note that, without a timestamp parameter passed to date() it uses the current time() instead
$sql = "SELECT * FROM `posts` WHERE `users_date_post` = '$date'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
echo $row['post_name'] . $row['users_date_post']; //output something from the posts
}
//Here's how to find all posts for a range of dates
$startdate = date('Y-m-d',$starttimestamp);
$enddate = date('Y-m-d',$endtimestamp);
//Yet again, date ranges need to be pulled in from somewhere, like $_GET or a POSTed form.
//Can also just pull in a formatted date rather than a timestamp and use it straight up instead, rather than going through date()
$sql = "SELECT * FROM `posts` WHERE `users_date_post` BETWEEN '$startdate' AND '$enddate'";
//could also do:
//"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$endate'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
//output data
}
To find posts for a specific user you would modify the statement to be something like:
$userid = 5; //Pulled in from form or $_GET or whatever
"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$enddate' AND `userid` = $userid"
To dump the result into an array do the following:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row=mysql_fetch_assoc($result))
{
$newarray[]=$row
}
What you probably want to do is this:
$users = array("Pete", "Jon", "Steffi");
$users = array_map("mysql_real_escape_string", $users);
$users = implode(",", $users);
..("SELECT * FROM users_newest_post WHERE FIND_IN_SET(user, '$users')");
The FIND_IN_SET function is a but inefficient for this purpose. But you could transition to an IN clause with a bit more typing if there's a real need.
$sql = 'SELECT * FROM `users_newest_post` WHERE username IN (' . implode(',', $users) . ')';

faster mysql query

Is there a faster way to do this?
$data1 = mysql_query(
"SELECT * FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error());
$num_results = mysql_num_rows($data1);
$data2 = mysql_query(
"SELECT sum(type) as total_type FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error());
while($info = mysql_fetch_array( $data2 )){
$count = $info['total_type'];
}
$total = number_format(($count/$num_results), 2, ',', ' ');
echo $total;
Cheers!
Looking at your queries, I think you're looking for something like this:
SELECT SUM(type) / COUNT(*) FROM table1 WHERE ...
SELECT COUNT(*) AS num_results, SUM(type) AS total_type FROM table1
WHERE id = $id and type = $type
This single query will produce a one-row result set with both values that you want.
Note that you should use a parameterized query instead of direct variable substitution to avoid SQL injection attacks.
Also, I'm guessing that SUM(type) isn't what you really want to do, since you could calculate it as (num_results * $type) without the second query.
$data1 = mysql_query("SELECT sum(type) as total_type,count(*) as num_rows FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error());
$info = mysql_fetch_array( $data1 );
$count = $info['total_type'];
$num_results = $info['num_rows'];
$total = ($count/$num_results);
echo $total;
In general: SELECT * can be 'shortened' to e.g. SELECT COUNT(*), if all you care about is the number of matching rows.
One line:
echo number_format(mysql_result(mysql_query("SELECT SUM(type) / COUNT(*) FROM table1 WHRE id = $id AND type = '$type'"), 0), 2, ',', ' ');

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories