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.
Related
I have 4 tables:
clients, pricelist, result and result_details
I want to generate a form where the transaction_id, name, test_name and result appear on it. I have done a select for the name but I can't figure out a select for the test_name and result.
I want something like this [pdf][5]
$result=mysqli_query($con,"SELECT r.transaction_Id,r.client_id,r.result_id,r.test_id,t.test_id,t.result,p.test_id,p.Name,c.Id,c.surName,c.firstName,c.dob,c.Gender FROM result r
JOIN result_details t
on r.test_id = t.test_id
left JOIN pricelist p ON r.test_id = p.test_id
left JOIN clients c ON r.client_id = c.Id")or die(mysqli_error());
$r=mysqli_query($con,"SELECT DISTINCT id,firstName,surName,Gender,dob FROM clients join result WHERE result.client_id=clients.Id")or die(mysqli_error());
while ($row = mysqli_fetch_array ($r)) {
$id=$row['id'];
$clientfirstname=$row['firstName'];
$surname=$row['surName'];
$gender=$row['Gender'];
$dob=$row['dob'];
$t=mysqli_query($con,"SELECT transaction_Id FROM transaction WHERE clientId=$id") or die(mysqli_error());
while ($test = mysqli_fetch_array ($t)) {
$transaction=$test['transaction_Id'];
$m=mysqli_query($con,"SELECT test_id,result_id from result where client_id=$id")or die(mysqli_error());
while ($q = mysqli_fetch_array ($m)) {
$test_id=$q['test_id'];
$result_id=$q['result_id'];
$z=mysqli_query($con,"SELECT Name from pricelist where test_id=$test_id")or die(mysqli_error());
while ($x = mysqli_fetch_array ($z)) {
$name=$x['Name'];
$query=mysqli_query($con,"SELECT result from result_details where result_id=$result_id")or die(mysqli_error());
while ($query1 = mysqli_fetch_array ($query)) {
$result=$query1['result'];
}
}
}
}
}
Just add:
GROUP BY AcctNo, OrderDate, Charge
HAVING COUNT(1) = 1
The GROUP BY groups all rows with the same field1, field2, ... and Charge together, then the HAVING COUNT(1) = 1 shows only the rows where there was just 1 progenitor. I hope it will work
Can I select more tables using this?
$table = "users";
$query = mysql_query("SELECT title, smalltitle, FROM $table ORDER BY date DESC");
while($result= mysql_fetch_array($query))
{
echo'<div id="title"> ';
echo'<p>'.$result['title'].'</p>';
echo'</div>';
echo'<div id="name"> ';
echo'<p>'.$result['name'].'</p>';
echo'</div>';
}
I want title/smalltitle from table "users" and name/text from table "gmsg"
Use this query -
"SELECT users.title, users.smalltitle, gmsg.name FROM users, gmsg $where_condition ORDER BY users.date DESC"
$where_condition would be the condtion to match users & gmsg like -
$where_condition = "users.id = gmsg.user_id"; //Or whatever it is
Yes, with JOIN. Documentation for use JOIN in Mysql here.
Sample:
SELECT * FROM t1 LEFT JOIN (t2, t3, t4)
ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)
$table = "users";
$table2 = "gmsg";
$query = mysql_query("SELECT a.title, a.smalltitle, b.name, b.text FROM $table a, $table2 b ORDER BY a.date DESC");
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';
I'm attempting to execute 4 prepared statement within a mysqli_fetch_row while loop. Currently my code is outputting NULL or empty values for all queries. This is my first time using prepared statements and I am trying to convert my code from mysql queries to mysqli. My code is below:
$users = mysqli_query($link, "SELECT id FROM users WHERE approved = '1'");
while ($user = mysqli_fetch_row($users)) {
if ($twitter_username_query = mysqli_prepare($username_query, "SELECT username FROM personas WHERE user_id = ?")) {
mysqli_stmt_bind_param($username_query, "d", $user[0]);
mysqli_stmt_execute($username_query);
mysqli_stmt_bind_result($username_query, $username);
mysqli_stmt_fetch($username_query);
mysqli_stmt_close($twitter_username_query);
}
if ($count_user_clicks = mysqli_prepare($count_user_clicks, "SELECT count(distinct txid) FROM users_clicks WHERE user_id = ?")) {
mysqli_stmt_bind_param($count_user_clicks, "d", $user[0]);
mysqli_stmt_execute($count_user_clicks);
mysqli_stmt_bind_result($count_user_clicks, $user_clicks);
mysqli_stmt_fetch($count_user_clicks);
mysqli_stmt_close($count_user_clicks);
}
if ($count_user_installs = mysqli_prepare("SELECT count(txid) FROM (SELECT txid FROM users_installs WHERE user_id = ? GROUP BY txid) table1")) {
mysqli_stmt_bind_param($count_user_installs, "d", $user[0]);
mysqli_stmt_execute($count_user_installs);
mysqli_stmt_bind_result($count_user_installs, $user_installs);
mysqli_stmt_fetch($count_user_installs);
mysqli_stmt_close($count_user_installs);
}
if ($calc_user_cost = mysqli_prepare($calc_user_cost, "SELECT sum(earnings) FROM (SELECT max(cost) as earnings FROM users_clicks WHERE user_id = ? GROUP BY txid) table1")) {
mysqli_stmt_bind_param($calc_user_cost, "d", $user[0]);
mysqli_stmt_execute($calc_user_cost);
mysqli_stmt_bind_result($calc_user_cost, $user_cost);
mysqli_stmt_fetch($calc_user_cost);
mysqli_stmt_close($calc_user_cost);
}
if ($user_clicks == '0') {
$user_conv = 0;
} else {
$user_conv = ($user_installs / $user_clicks) * 100;
}
echo "<tr>";
echo "<td><b>".$username."</b></td>";
echo "<td>".number_format($user_clicks)."</td>";
echo "<td>".number_format($user_installs)."</td>";
if ($user_installs[0] == '0') {
echo "<td>$0.00</td>";
} else {
echo "<td>$".number_format($user_cost / $user_installs, 2)."</td>";
}
echo "<td>".number_format($user_conv, 2)."%</td>";
echo "</tr>";
}
Use a single query that JOINs all the subqueries:
SELECT u.id, p.username, IFNULL(c.clicks, 0) AS clicks, IFNULL(i.installs, 0) AS installs, IFNULL(e.earnings, 0) AS earnings
FROM users AS u
JOIN personas AS p ON p.user_id = u.id
LEFT JOIN (
SELECT user_id, COUNT(DISTINCT txid) AS clicks
FROM user_clicks
GROUP BY user_id) AS c ON c.user_id = u.id
LEFT JOIN (
SELECT user_id, COUNT(DISTINCT txid) AS installs
FROM user_installs
GROUP BY user_id) AS i ON i.user_id = u.id
LEFT JOIN (
SELECT user_id, SUM(earnings) AS earnings
FROM (SELECT user_id, txid, MAX(cost) AS earnings
FROM user_clicks
GROUP BY use_id, txid) AS table1
GROUP BY user_id) AS e
WHERE u.approved = 1
I am trying to refactor this code a bit. Originally I had two different models, both extending MY_Model. However, most of the code was repetitive so now I am having First_model extend MY_Model and Second_model extends First_model. I cleaned up most of code from Second_model that it inherits from First_model, but I have several methods within Second_model that are only slightly different from the same method in First_model. Consider the following code:
First_model
class First_model extends MY_Model
{
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date('Y');
$month = date('n');
$sql = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
post.ts_created,
UNIX_TIMESTAMP(post.ts_created) post_timestamp,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
sum(ka.karma) monthly_karma
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (SELECT
IFNULL(u_all.id, user.id)
FROM UserAccounts ua
INNER join Users u ON u.id = ua.user_id
LEFT join Users u_all ON u_all.facebook_uid = u.facebook_uid
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year}
AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
$query = $this->db->query($sql);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row["id"]] = $row;
}
return $functionResults;
}
}
Second_model
class Second_model extends First_model
{
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date("Y");
$month = date("n");
$sql = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
UNIX_TIMESTAMP(post.ts_created) ts_created,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
SUM(ka.karma) monthly_karma,
post.answer_status_flags
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (
SELECT
IFNULL(u_all.id, user.id)
FROM
UserAccounts ua
INNER JOIN Users u ON (u.id = ua.user_id)
LEFT OUTER JOIN Users u_all ON (u_all.facebook_uid = u.facebook_uid)
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year} AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
$query = $this->db->query($sql);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row['id']] = $row;
}
return $functionResults;
}
}
Notice the only thing different is the query in the $sql variable. I am wondering can I somehow make the method in the first model protected and only change the query in the second? Or is there a more efficient way to trim down this code? I have several methods this same thing applies to and it seems a bit much to keep redefining the methods in the new Class.
I would think about pass the $sql as a variable in your models:
In your First Model you would have:
private $sqlPostId = '';
public function __construct() {
$this->sqlPostId = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
post.ts_created,
UNIX_TIMESTAMP(post.ts_created) post_timestamp,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
sum(ka.karma) monthly_karma
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (SELECT
IFNULL(u_all.id, user.id)
FROM UserAccounts ua
INNER join Users u ON u.id = ua.user_id
LEFT join Users u_all ON u_all.facebook_uid = u.facebook_uid
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year}
AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
}
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date('Y');
$month = date('n');
// Here you use the defined variable in the constructor
$query = $this->db->query($this->sqlPostId);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row["id"]] = $row;
}
return $functionResults;
}
And then you just have to change the SQL in the construct function in your second Model and go.