remove duplicate camma from mysql query - php

I am trying to fetch data with mulyiple value with Mysql IN operator but problem I am getting to much (,,,).
Here is my query :
$get_id = "select rel_blog from pages";
$resu = mysql_query($get_id);
$p_id="";
$rel_b="";
$i = 1;
while ($page_id = mysql_fetch_array($resu)){
$p_id.= $page_id['page_id'];
$rel_b.= $page_id['rel_blog'];
}
$p_id."<br>";
echo $rel_b."<br>";
echo $getblog = "SELECT * FROM pages WHERE rel_blog IN ($rel_b) order by add_date desc limit 7";
Ouery output is Like this this is not proper form so please help me .
SELECT * FROM pages WHERE rel_blog IN
(,114,93,126108default,,,,default,,,,default,,default,,,default,,default,,,,,,,default,,default,,,default,,default,,,,,,,,,,,,,,,,,,,,,,,,,,123,145,144,148,81,107default,,,,,default,,,,,,145,138,118default,,,,,,default,,,,,,,default,,,,,,,default,,,,,,,default,,,118default,,,,default,,,,,,,,default,,,,,,,,,default,,default,,,,,,,,default,,,,,,,,,default,,default,,,,,default,,,,,,default,,,,,,,,,default,,,,,,,,default,,,,,default,,,,,,,123,122,125,113default,,,default,,,default,,124,145140default,,,,,,,,,,,,,default,,,,,,,,default,,,default,,,default,,,,default,,,,default,,default,,,,default,,,default,,,default,,default,,,,,,,default,,,,,,default,,,,default,,,,,,default,,,default,,,,137default,,,,,,,default,,,default,,,default,,,,,,default,,,,,,,,,,default,,,,,,,,82,83default,,,,,,default,,,,default,,,,default,,,default,,,default,,,,default,,,,default,,,,default,,,,default,,,default,,,,default,,,,default,,,default,,,default,,,,,,default,,,,,,default,,,,,default,,,default,,,,,default,,,,,default,,,,default,,,default,,default,,default,,default,,,,,,,default,,,,default,,default,,,,default,,,,default,,,,default,,,,,default,,,,default,,,,,default,,,,,,,default,,,,default,,,,,default,,,,,,default,,,,,,,default,,,,,,default,,,,,,,default,,default,,default,,,,,default,,,default,,,default,,,default,,,,default,114,default,,,,,,117,116default,,,,,default,,,,117,116default,,,,default,,,,default,,,,,default,,,,default,,,,,default,,,,default,,,default,,default,,,,,,default,,,,,,default,,,,,108default,,,,118,129,121,143,80,82,81,148,117,146,107,88,118,82,80,81,148,143,123,118,107,142,116,110,128,127,111,109,125,113,123,118,85,118,128,109,126,93,114,82,142,108,111,90,113,123,144,148,108,107,142,116,115,110,128,127,113,118,144,146,80,148,107,143,135,125,143,110,115,118,132,146,80,123,81,148,107,116,108,109,125,135,113,123,144,118,116,108,127,147,125,123,144,129,107,142,112,116,135,113,123,144,132,118,107,85,123,144,118,82,148,107,123,132,146,148,107,108,122,89,136,146,80,81,117,148,142,107,110,147,119,82,80,145,129,146,80,148,107,111,109,125,113,123,118,148,81,107,131,115,109,121,125,135,113,123,144,107,131,126,93,141,114,124,139,113,91,144,118,81,117,148,107,142,115,143,135,91,118,142,116,87,143,140,123,144,132,145,129,146,82,80,117,91,118,148,137,113,141,93,143,136,123,144,146,82,118,148,85,112,108,127,122,87,143,141,91,144,146,80,82,81,117,148,107,115,109,91,129,146,82,80,117,148,81,142,107,110,130,138,89,126,113,default,default,118,146,82,81,148,107,142,115,109,126,default,123,144,145,80,146,82,81,117,142,128,138,135,93,140,123,144,145,132,82,80,117,83,142,130,140,145,129,82,80,81,108,111,138,89,143,125,145,123,118,82,80,81,117,88,112,108,147,139,119,140,123,144,118,80,82,81,142,107,85,108,115,114,144,118,129,146,80,81,83,120,148,107,142,128,127,110,115,91,123,145,82,117,146,81,80,148,82,80,117,81,148,83,120,107,142,88,131,118,129,146,80,117,107,83,88,142,130,89,125,139,134,113,145,144,118,132,123,82,80,146,81,148,83,123,91,137,140,134,139,113,141,124,93140,150,150)
order by add_date desc limit 7

Actually I can't figure out how you are getting even a single comma... This is how you can try it out.
$get_id = "select rel_blog,page_id from pages";
$resu = mysql_query($get_id);
$p_id="";
$rel_b="";
$i = 1;
while ($page_id = mysql_fetch_array($resu)){
$p_id.= $page_id['page_id'];
if($page_id['rel_blog']!=="" && $page_id['rel_blog']==="default") {
$rel_b.= $page_id['rel_blog'] .",";
}
}
$p_id."<br>";
$rel_b = substr($rel_b,0,-1); // get rid of the last comma
echo $rel_b."<br>";
echo $getblog = "SELECT * FROM pages WHERE rel_blog IN ($rel_b) order by add_date desc limit 7";

You can do this before your query.
$rel_b = preg_replace('/,+/', ',', trim($rel_b, ','));
This will remove repeated commas as well as commas from beginning and end of the string.

Try using implode():
$get_id = "select rel_blog from pages";
$resu = mysql_query($get_id);
$p_id = array();
$rel_b = array();
$i = 1;
while ($page_id = mysql_fetch_array($resu)){
$p_id[] = $page_id['page_id'];
$rel_b[] = $page_id['rel_blog'];
}
$p_id = implode(',', $p_id);
$rel_b = implode(',', rel_b);
echo $getblog = "SELECT * FROM pages WHERE rel_blog IN ($rel_b) order by add_date desc limit 7";

Related

How to fetch single row data from php?

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.

Random row selection using MySQL returns NULL

I am trying to get a random row from MySQL table but all three attemps:
$query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
give a NULL result in mysql_query($query).
Higher up my PHP code I obtain a row from the same table OK by specifying WHERE, so I don't understand why I can't retrieve a random one.
Here is the code snippet:
$query = "SELECT uid,clu FROM uable WHERE un = '$un'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$resultid = mysql_fetch_assoc($result);
$uid = $resultid['uid'];
file_put_contents('debugging.txt',__LINE__.' - $uid = '.var_export($uid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE uid = $uid AND cn = '$cn'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$cr = mysql_fetch_assoc($result);
$cid= $cr['cid'];
file_put_contents('debugging.txt',__LINE__.' - $cid= '.var_export($cid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM fable WHERE cid= '$cid'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
file_put_contents('debugging.txt',__LINE__.' - $result = '.var_export($result,true).PHP_EOL,FILE_APPEND);
$fr = mysql_fetch_assoc($result);
file_put_contents('debugging.txt',__LINE__.' - $fr = '.var_export($fr,true).PHP_EOL,FILE_APPEND);
echo '<form action="'.$_SERVER['PHP_SELF'].’" method="post">';
if (!$fr) {
$o= $cn;
while ($o= $cn) {
// $ac = mysql_query("SELECT * FROM table") or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
// $num_rows = mysql_num_rows($ac);
//file_put_contents('debugging.txt',__LINE__.' - $num_rows = '.$num_rows.PHP_EOL,FILE_APPEND);
// --$num_rows;
// $query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
// $query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
$resultid = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($resultid);
$o= $opr['cn'];
}
file_put_contents('debugging.txt',__LINE__.' - $query = '.$query.PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $resultid = '.var_export($resultid,true).PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $op[\'cid\'] = '.$op['cid'].PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE cid= ".$op;
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($opr);
$o= $opr['cn'];
$od= $opr['description'];
echo '<p>'.$op;
if ($od<> '') {
echo ','.$odesc;
}
echo '</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
} else {
echo '<p>'.$fr['p'].'</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
}
echo '</form>';
The resulting debugging.txt:
24 - $uid = '4'
29 - $cid = '21'
32 - $result = NULL
34 - $fr = false
These queries look OK, but I think you're starting at the wrong place. When you're uncertain how to frame something in SQL, open up a SQL client like SequelPro or Navicat and try writing a few queries by hand until you get the result you want. (Also this gives you a chance to double-check the contents of relevant tables and ensure the expected data are there.) Then you can go back into the PHP with full confidence that the SQL code is correct, so if there's a problem it must be with the PHP (either the variables you inject into a Mysql statement, or the way you call that statement).

mySQL Order by Most Commented and Least Commented

I'm trying to order a list of items based on the amount of comments for each topic as shown below:
$page = $_GET['page'];
$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");
if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];
//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}
What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber
The first query should be:
SELECT t.*, COUNT(c.topic_id) AS count
FROM topic AS t
LEFT JOIN comments AS c ON c.topic_id = t.topic_id
WHERE t.cat_id = '$page'
GROUP BY t.topic_id
ORDER BY count
LIMIT $start, $per_page
You can get $commentnumber with:
$commentnumber = $rows['count'];
You don't need the second query at all.
First of all you have error here
echo "divs in order from least to greatest "number = $num_rows"";
It should be
echo "divs in order from least to greatest number = " . $num_rows . "";
And about the most commented try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY column DESC/ASC";
Or if there is not count column try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY COUNT(column) DESC/ASC";

Echo the 2 last columns of tabel

I have a table and i want to echo the 2 last rows of my tabel, I used the below code but just the last one showed, what is the problem.
$result1 =(mysql_fetch_array(mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")));
Print $result1['time'];
mysql_fetch_array = 1 fetch.
do it again for fetching 2nd result.
Also, use mysqli eh.
You're doing mysql_fetch_array only one time, so it gets the first element. If you want to get all the elements, then do it again, or use a loop.
Something like:
$query = "SELECT * FROM $table ORDER BY id DESC LIMIT 2";
while($row = mysql_fetch_array(mysql_query($query) )
{
echo $row['time'].'<br>';
}
For 2 Or more rows you need to loop it
$sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")
while($row=mysql_fetch_array($sql))
{
echo $row['time']."<br>";
}
$query = mysqli_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2");
while ($result = mysqli_fetch_array($query)) {
echo $result['time'];
}
Gives out every return of your database (2 in this case). You should use mysqli_-functions.
Maybe you should try like this, since mysql_fetch_array returns only one row
while ($row = mysql_fetch_array($yourQuery)) {
echo $row["yourAlias"];
}
Further details here : http://fr2.php.net/manual/en/function.mysql-fetch-array.php
My solution:
$limit = 2;
$sql = "SELECT * FROM $table ORDER BY id DESC LIMIT $limit";
$result = mysql_query($sql);
$array = array(); $i = 0;
while($row = mysqli_fetch_array($result))
{
$array[$i] = $row;
$i++;
}
var_dump($array[0]);
var_dump($array[1]);

SQL QUERY returning all results using OR in WHERE statement

Hoping I am just missing something simple here:
$sql = "Select * FROM user_info, user_login WHERE user_login.status = '0' OR user_login.status = '2' AND user_info.uid = user_login.uid";
$db = new connection();
$results = $db->query($sql);
$user = array();
while($info = mysql_fetch_array($results))
{
$user[] = $info;
}
$total = count($user);
//TEST the amount of rows returned.
echo $total;
for ($i = 0; $i < $total; $i++)
{
//echo data;
}
just trying to pull all data that has the user_login.status field set to "0" or "2" but it shows everything thing and it shows the items marked as 2 twice.
Does anyone see my issue?
Your precedence is getting whacked because of missing parentheses:
SELECT DISTINCT *
FROM user_info, user_login
WHERE (user_login.status = '0' OR user_login.status = '2')
AND user_info.uid = user_login.uid
Without seeing the data I can't give you more than a SELECT DISTINCT with regards to the duplicate records.
Select * FROM user_info, user_login WHERE (user_login.status = '0' OR user_login.status = '2') AND user_info.uid = user_login.uid
Order of precedence :)

Categories