MySQL - Select differently - php

I have this query, which selects a distinct value for a column, but I need something else in that query too. I need it to fetch a different row associated with the main select.
Let me illustrate...
This is my query:
$sql = 'SELECT DISTINCT user_id FROM ' . DONATION_SECURITY_TABLE;
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
mysql_free_result($result);
return $rows;
As you see it returns this query returns the DISTINCT of user_id.
If I use a function like this in a double foreach loop created using the return of the query above:
public function get_donor_status($user_id)
{
global $db;
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$payment_status = $row['payment_status'];
$db->sql_freeresult($result);
return $payment_status;
}
This function would return Completed for user_id 2, but I want it to say Pending instead. How would I change my query so it returns the last value for the corresponding user_id?
If I'm not clear enough, please let me know so I can reexplain.

Just select the last row for the user:
"SELECT payment_status FROM " . DONATION_SECURITY_TABLE . " WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1"

How about this?
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1";

You can actually get everything in one SQL statement, no need for a double loop:
SELECT
user_id, payment_status
FROM
DONATION_SECURITY_TABLE t1
WHERE
donation_id = (select max(donation_id) from DONATION_SECURITY_TABLE t2 WHERE t2.user_id = t1.user_id)
ORDER BY
user_id

Related

CodeIgniter get table count rows

I am new in CodeIgniter, I want to count all rows from database table but i use limit in query and i want all count without use limit how can i do ?
my code is below :
$sql = " SELECT intGlCode,fkCategoryGlCode,'C' as acctyp,varEmail,varContactNo as phone,CONCAT(varFirstName,' ',varLastName) as name,dtCreateDate,chrStatus,varMessage as message
FROM " . DB_PREFIX . "Customer WHERE varEmail='$userEmail'
UNION
SELECT intGlCode,'' as fkCategoryGlCode,'P' as acctyp,varEmail,varPhoneNo as phone,varName as name,dtCreateDate,chrStatus,txtDescription as message FROM
" . DB_PREFIX . "Power WHERE varEmail='$userEmail' ORDER BY intGlCode DESC
LIMIT $start, $per_page ";
$query = $this->db->query($sql)
i use limit for pagination but i want to get all record from table.
You can add new column in both above and below UNION queries. It will be like below.
select (select count(*) from your_query), your_columns from query_above_union
UNION
select (select count(*) from your_query), your_columns from query_below_union
your_query = your full actual query your are using currently.
Although I am not sure about Codeigniter. But sure about SQl.
* If you count all records with all data including limit, than you can use this code. please check it. I hope it will works for you.*
$countsql = " SELECT intGlCode,fkCategoryGlCode,'C' as acctyp,varEmail,varContactNo as phone,CONCAT(varFirstName,' ',varLastName) as name,dtCreateDate,chrStatus,varMessage as message
FROM " . DB_PREFIX . "Customer WHERE varEmail='$userEmail'
UNION
SELECT intGlCode,'' as fkCategoryGlCode,'P' as acctyp,varEmail,varPhoneNo as phone,varName as name,dtCreateDate,chrStatus,txtDescription as message FROM
" . DB_PREFIX . "Power WHERE varEmail='$userEmail' ORDER BY intGlCode DESC";
$sql = $countsql. " LIMIT $start, $per_page";
$totalRecords = $this->db->query($countsql);
$result["total_rows"] = $totalRecords->num_rows();
$query = $this->db->query($sql);
$result["list"] = $query->result_array();

PHP Run query on SHOW TABLES results

How do I go about running a query on tables from a previous SHOW TABLES query? What I'm trying to do is create a PHP script that runs every 24 hours that sorts a table by "verified" descending and "votes" descending and update "nomnom" on the top result, for every table in the database.
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan = (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE " . $row[0] . " SET nomnom=0 verified=0; UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $row[0] . ' done<br>';
}
} else {
echo 'query 0';
}
This correctly echos every table name followed by done, but isn't actually updating the tables. What am I missing?
UPDATE
So I've determined that the following should work:
$sql = "SET #clan := (SELECT `clan` FROM " . $row[0] . " ORDER BY `verified` DESC, `votes` DESC LIMIT 1); UPDATE " . $row[0] . " SET `nomnom`=0, `verified`=0; UPDATE " . $row[0] . " SET `nomnom`=1 WHERE `clan`=#clan";
by echoing $sql and running the queries returned through phpmyadmin without changing anything.
Here's a line that is echoed.
SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
It just for some reason isn't actually doing it when using
$conn->query($sql);
UPDATE 2
Figured out a way to make it work. Would mark my answer but I can't for 2 days...
Try this query
$sql = SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
This should work
Had to split the query into 3 separate queries. Full working code:
$conn = new MySQLi($servername, $username, $password, $dbname);
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan := (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1);";
$sql2 = "UPDATE " . $row[0] . " SET nomnom=0, verified=0;";
$sql3 = "UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $conn->error . '<br>';
$conn->query($sql2);
echo $conn->error . '<br>';
$conn->query($sql3);
echo $conn->error . '<br>';
}
} else {
echo 'query 0';
}
If anyone would like to post how to make this a proper multi_query without getting queries out of sync errors, be my guest. I cba doing that lol.

if statement to check if mysql row exists, then selecting next query

I'm attempting to select a query to use based on the number of rows returned by a test result.
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$result = "SELECT FROM Notifications WHERE UserID=$id";
$r = e_mysql_query($result);
$row = mysql_fetch_array($r);
$num_results = mysql_num_rows($result);
$result = '';
if ($num_results != 0) {
$result =
"SELECT U.UserID,U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U, Notifications N " .
" WHERE U.LocationID=0 " .
" AND N.UserID='$id'";
} else {
$result =
"SELECT UserID, FirstName, LastName," .
" DATE_FORMAT(BirthDate, '%m-%d-%Y') AS BirthDate " .
" FROM Users " .
" WHERE LocationID = 0 " .
" AND UserID ='$id'";
}
echo $result;
e_mysql_result($result); //Bastardized/homegrown PDO
if ($row = mysql_fetch_assoc($result)) {
$retValue['userInfo'] = $row;
...
I'm checking the Notifications table to see if the UserID exists there, if it doesn't it loads what does exist from the Users table, if it does, then it loads everything from the Notifications table.
I'm echoing out the $result and the proper statement is loaded, but it doesn't execute. When I run the concatenated query I get from the PHP preview, it returns just fine.
Before I had to if/else this, I was running the first query, loading everything from the Notifications table, and it was loading just fine. What am I missing?
You can do the whole thing with one query with a LEFT JOIN.
$query= "SELECT U.UserID, U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U " .
" LEFT JOIN Notifications N " .
" ON U.UserID = N.UserID " .
" WHERE U.UserID = '$id'";
You are missing execute a query with mysql_query() on all $result
Also change (query variable should be quoted) so change your all variables $id quoted
$result = "SELECT FROM Notifications WHERE UserID=$id";
to
$result = "SELECT FROM Notifications WHERE UserID='$id'";
$r = mysql_query($result);
Note :- mysql_* has been deprecated use mysqli_* or PDO

How to get sum of a column in Zend framework using model and controller

I am looking for a way to get the sum of a column. The query i am using looks like this:
public function gradeRound($rating)
{
$sql = mysql_query("Select SUM(rating) AS grades FROM" . $this->_prefix . "media_set_rating WHERE set_id = set_id");
mysql_real_escape_string($rating->rating);
$row = mysql_fetch_assoc($sql);
$grades = $row['grades'];
}
I am not sure how to get this properly formatted for the controller. right now my controller has this.
i put a text box on the page and echoed $grades - this is also included in the view as so:
$this->_view->assign('grades', $grades);
so that i can use it.
I tried replacing $setId with $rating both of which are being requested at the top.
I do not get anything out of my echo. I had -1 in there earlier. i am not sure where it was getting that from. I was trying different methods and got different results.
appreciate any hints or clues as to how to do this.
thanks
Revised 2:17 EST May 27 2013
Thanks Niko. I must be getting tired!
Here is the revised query:
public function gradeRound($rating)
{
$sql = sprintf("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating
WHERE set_id = set_id");
$sum = mysql_query($sql);
$row = mysql_fetch_assoc($sum);
$grades = $row['grades'];
return $grades;
}
$grades = $setDao->gradeRound($setId);
Your SQL query looks rather odd. Depending on the type of "set_id", it is supposed to look like this:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = '". mysql_real_escape_string($rating->rating) ."'"
);
for ยด$rating->rating` being a string. For an integer, it should be:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = ". (int) $rating->rating
);
And in total (adding also a return statement):
public function gradeRound($rating)
{
// expecting "set_id" to be an integer field
$result = mysql_query("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating WHERE set_id = ". (int) $rating->rating);
$row = mysql_fetch_assoc($result);
return $row['grades'];
}
Hope this will help You !
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );

sql statement works in phpMyAdmin but won't work in mysql_query

Really stuck on something. I'm trying to update a database and the code looks write - and if I echo it out and paste it directly into phpMyAdmin it works perfectly - but the code itself doesn't work... I have spend a day so far trying to figure out why it's not working and I'm completely out of ideas...
function restoreSession()
{
mysql_connect("theHost", "root", "rootPWD") or die(mysql_error());
mysql_select_db("myDatabase") or die(mysql_error());
$restore_cmd = 'UPDATE wp_dor_cart66_sessions SET user_data = (SELECT user_data FROM wp_dor_cart66_stored_sessions WHERE ip_address = "' . $_SERVER['REMOTE_ADDR'] . '")';
$clean_up = "DELETE FROM `wp_dor_cart66_sessions` WHERE `ip_address` = \"" . $_SERVER['REMOTE_ADDR'] . "\" AND id NOT IN (SELECT id FROM ( SELECT id FROM `wp_dor_cart66_sessions` ORDER BY id DESC LIMIT 1 ) user_data )";
mysql_query($clean_up) or die('Query failed: ' . mysql_error());
$result = mysql_query($restore_cmd) or die('Query failed: ' . mysql_error());
echo "<br/>";
echo $restore_cmd;
echo "<br/>";
var_dump($result);
echo "<br/>";
print_r($result);
}
The resulting output looks like:
UPDATE wp_dor_cart66_sessions SET user_data =
(SELECT user_data FROM wp_dor_cart66_stored_sessions
WHERE ip_address = "196.54.110.24");
bool(true)
1
It doesn't appear to have any errors - but I just can't get it to update. If it didn't work in phpMyAdmin - I'd know there was something wrong with the SQL - but it seems right... I'm just really out of ideas - any help would be greatly appreciated!
Here are the statements again with some formatting:
$restore_cmd = '
UPDATE
wp_dor_cart66_sessions
SET
user_data = (
SELECT
user_data
FROM
wp_dor_cart66_stored_sessions
WHERE
ip_address = "' . $_SERVER['REMOTE_ADDR'] . '"
)
';
$clean_up = "
DELETE FROM
`wp_dor_cart66_sessions`
WHERE
`ip_address` = \"" . $_SERVER['REMOTE_ADDR'] . "\"
AND id NOT IN (
SELECT
id
FROM
(
SELECT
id
FROM
`wp_dor_cart66_sessions`
ORDER BY
id DESC
LIMIT
1
) user_data
)
";
$restore_cmd = 'UPDATE wp_dor_cart66_sessions SET user_data = (SELECT user_data FROM wp_dor_cart66_stored_sessions WHERE ip_address = \"' . $_SERVER['REMOTE_ADDR'] . '\")';
need to escape the quotation marks
Looks like quoting error, Try this:
"UPDATE wp_dor_cart66_sessions SET user_data = (SELECT user_data FROM wp_dor_cart66_stored_sessions WHERE ip_address = '" . $_SERVER['REMOTE_ADDR'] . "')";
If could be that you have multiple results in your SELECT.
What if you do ...
$restore_cmd = 'UPDATE wp_dor_cart66_sessions SET user_data = (SELECT user_data FROM wp_dor_cart66_stored_sessions WHERE ip_address = "' . $_SERVER['REMOTE_ADDR'] . '" LIMIT 1)';
... note the LIMIT 1
Are you sure that the first query is not deleting all the matching rows?
I don't understand the "user_data" part at the end of the first query. But I would check the number of affected rows after each query to see if query is doing any affect on data and if it is, is it doing well or there's just some logical mistake.

Categories