I'm running one while inside another while but the second one is running only one time why and how can I fix it. I have also try with for but running again only once.
$sql = "SELECT DISTINCT season FROM search WHERE link = '$getid' Order by id asc";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($list = mysql_fetch_assoc($result))
{
$season = $list['season'];
$sql = mysql_query("SELECT * FROM search WHERE link = '$getid' and season = '$season'");
$episodes = mysql_num_rows($sql);
echo '1st';
$sqls = "SELECT * FROM search WHERE link = '$getid' and season = '$season' Order by id asc";
$results = mysql_query($sqls, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($lists = mysql_fetch_assoc($results))
{
$episode = $lists['episode'];
echo'2nd';
}
}
You are overriding the variables, use different ones:
$sql = "SELECT DISTINCT season FROM search WHERE link = '$getid' Order by id asc";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($list = mysql_fetch_assoc($result))
{
$season = $list['season'];
$sql2 = mysql_query("SELECT * FROM search WHERE link = '$getid' and season = '$season'");
$episodes = mysql_num_rows($sql2);
echo '1st';
$sqls = "SELECT * FROM search WHERE link = '$getid' and season = '$season' Order by id asc";
$results2 = mysql_query($sqls, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($lists2 = mysql_fetch_assoc($results2))
{
$episode = $list2['episode'];
echo'2nd';
}
}
Related
for ($i=$start; $i<$start+$scale && $i < $total_record; $i++)
{
$sql = "select * from memo where num = ?";
$stmh = $pdo->prepare($sql);
//mysql_data_seek($result, $i);
$row = mysql_fetch_array($result);
$sql2 = "select * from phptest.memo order by num desc";
$stmh2 = $pdo->query($sql2);
$stmh2->execute();
//$row = $stmh2->fetch(PDO::FETCH_ASSOC);
$row = $stmh->fetchColumn($i-1);
$memo_id = $row['id'];
$memo_num = $row['num'];
$memo_date = $row['regist_day'];
$memo_nick = $row['nick'];
$memo_content = $row['content'];
Hi guys i want fetch single row data by using PDO method instead of $row = $stmh2->fetch(PDO::FETCH_ASSOC); like mysqli_data_seek($result,$i);. What should i do?
$sql2 = "select * from phptest.memo order by num desc";
$stmh2 = $pdo->query($sql2);
$stmh2->execute();
while($r = $stmh2->fetch()) {$row[] = $r;}
Now $row[$i] should be getting you the same results as mysqli_data_seek($result,$i) would have.
IE: $row[0] would return the first row.
This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 11 months ago.
I'm trying to query a MySQL database using an array but I'm having trouble!
I have a table called clients, I want to be able to select 'name' from all rows whose 'sector' column is equal to $sectorlink.
I then want to put all the names into an array so I can perform my next query: select all rows from another table whose 'client' column is equal to one of the names returned from the first query. I'm doing something wrong because it returns a fatal SQL error. I'm getting confused with all the variables!
$sectorlink and $connection are the only variables that are defined outside of this code
Any suggestions?
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
foreach($row AS $key => $value){$temp[] = '"'.$value.'"';}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($row) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
}
The second query should use $thelist not $row, and it should be outside of the while loop. The foreach loop is unnecessary when processing a single row. You can access the name in $row with a simple $row[0]. Something like this (untested):
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$temp[] = '"'.$row[0].'"';
}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
Caution: Please be aware that your code is highly vulnerable to SQL injection attacks. It's fine for testing or internal development but if this code is going to be running the Fort Knox web site you're going to want to fix it up quite a bit. Just an FYI. :-)
Try This:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$client = $row['name'];
$query = "SELECT * FROM studies WHERE client='$client' ORDER BY date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
/* echo results here */
}
Couple of things. First you have an unnecessary loop there. Try:
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
To build your temporary array.
Second, the parts of the IN clause are strings, so when you implode, you'll need to enclose each value in quotes:
$thelist = "'". implode("','", $temp) . "'";
Lastly, in your query you are passing $row to the IN clause, you should be passing $thelist:
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
So altogether:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
$thelist = "'". implode("','", $temp) . "'";
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
I expect you'd be better off doing this in one query with a join:
$query = "SELECT COUNT(*) FROM `studies` INNER JOIN `clients` on studies.client = clients.name WHERE clients.sector = '$sectorlink' ORDER BY studies.date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
Following is my code,
$result1 = "SELECT emp_id FROM employee where manager_id=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
"emp_id: " . $row[0];
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
var_dump($myArrayOfemp_id);
$sql = "SELECT emp_id FROM emp_leaves WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
When I'am trying to use $myArrayOfemp_id variable in $sql query, It shows that error:
Array to string conversion in..
How can I fix it?
You are trying to convert an array into a string in the following line:
$sql = "SELECT emp_id FROM emp_leaves
WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";
$myArrayOfemp_id is an array. That previous line of code should be changed to:
$sql = "SELECT emp_id FROM emp_leaves
WHERE emp_id={$myArrayOfemp_id[0]} ORDER BY apply_date DESC";
I placed 0 inside {$myArrayOfemp_id[0]} because I'm not sure what value want to use that is inside the array.
Edited:
After discussing what the user wanted in the question, it seems the user wanted to use all the values inside the array in the sql statement, so here is a solution for that specific case:
$sql = "SELECT emp_id FROM emp_leaves
WHERE ";
foreach ($myArrayOfemp_id as $value)
{
$sql .= " emp_id={$value) || ";
}
$sql .= "1=2";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
$sql = "SELECT emp_id FROM emp_leaves WHERE emp_id in
(SELECT GROUP_CONCAT(emp_id) FROM employee where manager_id=".$userID.")
ORDER BY apply_date DESC";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
just change your query like above might solve your problem.
you can remove following code now. :)
$result1 = "SELECT emp_id FROM employee where manager_id=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
"emp_id: " . $row[0];
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
var_dump($myArrayOfemp_id);
I'm trying to update an older MySQL PHP method call but I end up calling the same SELECT call twice to achieve the same result. Is there a better way to do this?
Here is the original:
function updateProbabilities()
{
// first update the word count of each category
$rs = $this->con->select("SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id");
$total_words = 0;
while (!$rs->EOF()) {
$total_words += $rs->f('total');
$rs->moveNext();
}
$rs->moveStart();
if ($total_words == 0) {
$this->con->execute("UPDATE nb_categories SET word_count=0, probability=0 WHERE 1");
return true;
}
while (!$rs->EOF()) {
$proba = $rs->f('total')/$total_words;
$this->con->execute("UPDATE nb_categories SET word_count=".(int)$rs->f('total').",
probability=".$proba."
WHERE category_id = '".$rs->f('category_id')."'");
$rs->moveNext();
}
return true;
}
Here is my version:
function updateProbabilities() {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
$total_words = 0;
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$total_words += $row['total'];
}
if ($total_words >= 1) {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$proba = $row['total']/$total_words;
$count = (int)$row['total'];
$sql = "UPDATE nb_categories SET word_count=".$count.",
probability=".$proba."
WHERE category_id = '".$row['category_id']."'";
mysql_query($sql) or die (mysql_error());
}
}
else {
$sql = "UPDATE nb_categories SET word_count=0, probability=0 WHERE 1";
mysql_query($sql) or die (mysql_error());
}
return true;
}
Do you see any way I can avoid this second duplicate SELECT call?
The first time you run the query, add this to the while loop to store the results:
$rowarray[] = $row; // added to prevent running it twice
Then the second time it comes up, replace this:
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
with this:
foreach ($rowarray as $row) {
ALSO: move away from mysql_ functions, as they are deprecated and will soon be removed from PHP. Change to a PDO or MySQLi. You're already upating the code, may as well make that change too.
The mysql equivalent of $rs->moveStart() is:
mysql_data_seek($res, 0);
P.S. If you're rewriting into a new API, why are you using the deprecated mysql extension? You should use mysqli or PDO? They have similar methods for rewinding the cursor.
You can set the first query to a unique variable, and re-use the results of that query.
function updateProbabilities() {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
$total_words = 0;
$results = array();
while ($row1 = mysql_fetch_array($res, MYSQL_ASSOC)) {
$total_words += $row1['total'];
$results[] = $row1;
}
if ($total_words >= 1) {
foreach ($results as $row2) {
$proba = $row2['total']/$total_words;
$count = (int)$row2['total'];
$sql = "UPDATE nb_categories SET word_count=".$count.",
probability=".$proba."
WHERE category_id = '".$row2['category_id']."'";
mysql_query($sql) or die (mysql_error());
}
}
else {
$sql = "UPDATE nb_categories SET word_count=0, probability=0 WHERE 1";
mysql_query($sql) or die (mysql_error());
}
return true;
}
I have a query that gets 5 lines of data like this example below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
}
I want to run a query inside each results like this below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
but for some reason it's only display the first line when I add the query inside it. I can seem to make it run all 5 queries.
SELECT
t1.ref,
t1.user,
t1.id,
t2.domain,
t2.title
FROM
table AS t1
LEFT JOIN anothertable AS t2 ON
t2.domain = t1.ref
LIMIT
0, 5
The problem is that inside the while-cycle you use the same variable $result, which then gets overridden. Use another variable name for the $result in the while cycle.
You change the value of your $query in your while loop.
Change the variable name to something different.
Ex:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$qry = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$rslt = mysql_query($qry) or die(mysql_error());
if (mysql_num_rows($rslt) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
Use the following :
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query_domain = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result_domain = mysql_query($query_domain) or die(mysql_error());
if (mysql_num_rows($result_domain) )
{
$row_domain = mysql_fetch_row($result_domain);
$title = $row_domain['title'];
} else {
$title = "No Title";
}
echo "$ref - $title";
}
This is a logical problem. It happens that way, because you are same variable names outside and inside the loop.
Explanation:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
// Now $results hold the result of the first query
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
//Using same $query does not affect that much
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
//But here you are overriding the previous result set of first query with a new result set
$result = mysql_query($query) or die(mysql_error());
//^ Due to this, next time the loop continues, the $result on whose basis it would loop will already be modified
//..............
Solution 1:
Avoid using same variable names for inner result set
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$sub_result = mysql_query($query) or die(mysql_error());
// ^ Change this variable so that it does not overrides previous result set
Solution 2:
Avoid the double query situation. Use joins to get the data in one query call. (Note: You should always try to optimize your query so that you will minimize the number of your queries on the server.)
SELECT
ref,user,id
FROM
table t
INNER JOIN
anothertable t2 on t.ref t2.domain
LIMIT 0, 5
Learn about SQL joins:
SELECT table.ref, table.user, table.id, anothertable.title
FROM table LEFT JOIN anothertable ON anothertable.domain = table.ref
LIMIT 5
You're changing the value of $result in your loop. Change your second query to use a different variable.
it is not give proper result because you have used same name twice, use different name like this edit.
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query1 = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result1 = mysql_query($query1) or die(mysql_error());
if (mysql_num_rows($result1) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}