PHP and mysql_query issue - php

I have this code in PHP:
$sql = '
SELECT t1.name, t2.code, COUNT(t2.code) as cnt
FROM t1
LEFT JOIN t2
ON t2.code = t1.code2
WHERE (t2.input_date BETWEEN "2015-04-01" AND "2015-04-29")
AND t2.serial = 5
GROUP BY t2.code HAVING (t2.code>0)';
$Chartdata= mysql_query($sql) or die(mysql_error());
$arr = array();
while ($row = mysql_fetch_assoc($Chartdata)) {
$arr[] = $row;
}
echo json_encode($arr);
This code shows a blank page on my browser. I tried to delete the last one "AND" and "GROUP BY...", it shows 1 value.

Try just:
$sql = '
SELECT t1.name, t2.code, COUNT(*) as cnt
FROM t1
LEFT JOIN t2
ON t2.code = t1.code2
WHERE (t2.input_date BETWEEN "2015-04-01" AND "2015-04-29")
AND t2.serial = 5
AND t2.code>0
GROUP BY t2.code';

Related

How to create IF statement in MYSQL query WHERE statement

Is this possible to be done with SQL?
I need to make a SQL selection depending if a $query is false WHERE (u.id_user = ".$userId." OR fu.id_user = ".$userId." OR ff.id_user = ".$userId.")" ELSE "$query";
That's my starting point where both conditions have to be met:
$validatedSearchData = array(
"q"=>strip_tags($_GET["q"])
);
$query= " AND a.tags LIKE ".lib::$db->qstr("%".$validatedSearchData["q"]."%");
$feed = lib::$db->GetAll("SELECT SQL_CALC_FOUND_ROWS
a.*,
u.name,
fu.id_user AS fu_user_id,
ff.id_followed_user AS ff_user_id
FROM feed AS a
LEFT JOIN userfollow AS fu ON a.id_author = fu.id_user
LEFT JOIN userfollow AS ff ON a.id_author = ff.id_followed_user
INNER JOIN user_profiles AS u ON a.id_author = u.id_user
WHERE (u.id_user = ".$userId." OR fu.id_user = ".$userId." OR ff.id_user = ".$userId.")" . $query. "
GROUP BY a.id_article
");
Change this line
$query= " OR a.tags LIKE ".lib::$db->qstr("%".$validatedSearchData["q"]."%");
replace OR in the place of AND

Using php if...else statement with two queries

I have two queries that count the number of data for both "artists" and "groups" in my database. I want to display a message if there is data to display for either artists or groups (or both), and if the data returns 0 for both of them then not to display anything.
I have the following code which doesn't seem to work:
<?php if (($numrowsartists==0)OR($numrowsgroups==0)) {
} else {
echo "There is information to display.";
}
?>
Below are the queries I have:
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$numrowsartists = mysql_fetch_assoc($res);
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$numrowsgroups = mysql_fetch_assoc($res);
Thanks in advance. I'm sure it's probably a super basic fix but I'm still very new to php and would appreciate some help.
You should getthe value frorm the row eg using alias for column name
$query = "SELECT COUNT(*) as num_artists FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsartists = row['num_artists'];
$query = "SELECT COUNT(*) as num_groups FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsgroups = row['num_groups'];
There are several solutions, the easiest being the following:
if($numrowsartists[0]+$numrowsgroups[0] > 0)
However, as people have said, you shouldn't use mysql_* functions anymore.
Assuming the ID is user input, you should really use prepared statements.
Also, you can handle both tests in a single query:
$stmt = $con->mysqli_prepare("SELECT COUNT(1) as `count` FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = ?");
$stmt->bind_param('i',$id);
$stmt->execute();
if($stmt->get_result()->fetch_array()[0] > 0){
...
}else{
//message that nothing was found
}

How To Avoid Queries in loops

Hi how can i avoid queries like these?
sample query:
$sql = DB::getInstance()->prepare("SELECT tb_id1 FROM table1 WHERE duedate < ?");
$sql->execute(array($currentdate));
if($sql->rowCount()){
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$sql2 = DB::getInstance()->prepare("UPDATE table2 SET isOverdue = 1 WHERE tb_id2 = ?");
$sql2->execute(array($row["tb_id1"]));
}
}
You can use update with join and thus by not using any loop in PHP
update table2 t2
join table1 t1 on t1.tb_id1 = t2.tb_id2
set t2.isOverdue = 1
where
t1.duedate < ?

Why cant put my data into an associative array

I have about 20 tables in my db, im running query inside a while loop to get all that table data and store data of each table inside an array, looping and everything happens fine but storing part does not happen. can any body help me to store data of each table inside an array
code
while($row = mysql_fetch_array($table_count)){
$table = $row["TABLE_NAME"];
$excute = mysql_query("
SELECT DISTINCT b.ID, name, accountname, c.accountID, status, total_impr, min(a.timestamp), max(a.timestamp)
FROM $table a INNER JOIN bookers b on a.ID = b.ID INNER JOIN accounts c on b.accountID = c.accountID
WHERE a.timestamp > DATE_ADD(NOW(), INTERVAL -1 YEAR)
GROUP BY ID;") or die(mysql_error());
$result = mysql_fetch_assoc($excute);
$tables = array();
$tables .= $result;
}
print_r($tables);
There is little mistake in your syntax in foreach use this
foreach ($table as $tables) {
Correct syntax of forech is
foreach(array_expression as $variable)
{
}
Update====
$tables = array();
$i=0;
while($row = mysql_fetch_array($table_count))
{
$table = $row["TABLE_NAME"];
$excute = mysql_query("
SELECT DISTINCT b.ID, name, accountname, c.accountID, status, total_impr, min(a.timestamp), max(a.timestamp)
FROM $table a INNER JOIN bookers b on a.ID = b.ID INNER JOIN accounts c on b.accountID = c.accountID
WHERE a.timestamp > DATE_ADD(NOW(), INTERVAL -1 YEAR)
GROUP BY ID;") or die(mysql_error());
while($finalRes = mysql_fetch_assoc($excute))
{
$tables[$i][] = $finalRes;
}
$i++;
}
echo '<pre>';
print_r($tables);
And you are using this wrongly.

MYSQLI SELECT with Limit not working

I'm trying to find the number of rows in a table in the database depending on certain conditions with a limit feature so that i can count the number of rows there are matching the condition after a certain row in the table.
Thus i created my php query:
$q = $db->query("SELECT u.*, f.* FROM updates U LEFT JOIN friends f ON f.fid = u.userid WHERE f.uid = '$userid' ORDER BY u.up_id DESC LIMIT $limitID, 9999999");
$nr = $q->num_rows;
However even if there are more rows in the database after the $limitID, it says there are no rows.
If I try this:
$q = $db->query("SELECT u.*, f.* FROM updates U LEFT JOIN friends f ON f.fid = u.userid WHERE f.uid = '$userid' ORDER BY u.up_id DESC LIMIT $limitID");
$nr = $q->num_rows;
then it works, but it doesnt count after the $limitID. Any udeas?
According yo your query, it should be like
$sql = "SELECT count(*) FROM updates U
LEFT JOIN friends f ON f.fid = u.userid WHERE f.uid = ?";
// getting stuff using prepared statements
$row = $res->fetch_row();
$num = $row[0] - $limitID;
but I doubt it's really what you need either.
Using what Your Common Sense told me I managed to find an answer to my problem, so here it is:
$limitID = $upid;
$sql = "SELECT count(*) FROM updates u
LEFT JOIN friends f ON f.fid = u.userid WHERE
(f.uid = '$userid' AND u.up_id > '$limitID')";
$res = $db->query($sql);
$row = $res->fetch_row();
$num = $row[0];
if($num == 0){
// do nothing
} else {
echo "<span class='newPosts'>" .$num. " New Post"
. (($num>1)?'s':' ') . "</span>";
}
works perfectly

Categories