SQLite average function - php

I'm currently using the following code to use PHP to grab data from an SQLite database. This extracts all data from column1 where the date is greater than a date I specify. The output goes into $output, where I can then stick the data in a table.
class MyDB extends SQLite3
{
function __construct()
{
$this->open('database_name.sdb');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully<br /><br />";
}
$sql =<<<EOF
SELECT * FROM "archive" WHERE "dateTime" > $specified_time;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$output = $row['column1'];
}
I now want to get the average of values in 'column 2' (where the date is greater than a certain date) and put it into a PHP variable. This is the code I'm using but it's returning a blank. I've tried a few other things too, but to no avail.
$sql =<<<EOF
SELECT AVG("column2") FROM "archive" WHERE "dateTime" > $specifiedtime;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$output = $row['AVG("column2")'];
}
Any ideas?
Thanks.

Use an alias for your calculated column
SELECT AVG(column2) as avg_col2 FROM ...
Then you can name that column in PHP
$output = $row["avg_col2"];

Related

PHP ADODB - Reuse Query Result?

How does one reuse a query result with PHP ADODB, at the moment I am doing this, which I assume is inefficient? :
$query = "SELECT colname FROM table";
$result1 = $db->SelectLimit($query,10,-1);
$result2 = $db->SelectLimit($query,10,-1);
// 1ST RUN
while (!$result1->EOF) {
echo $result1->Fields('colname').'<br>';
$result1->MoveNext();
}
// 2ND RUN
while (!$result2->EOF) {
echo $result2->Fields('colname').'<br>';
$result2->MoveNext();
}
To answer my own question, need to use:
$result1->move(0);
so like this:
$query = "SELECT colname FROM table";
$result1 = $db->SelectLimit($query,10,-1);
// 1ST RUN
while (!$result1->EOF) {
echo $result1->Fields('colname').'<br>';
$result1->MoveNext();
}
// 2ND RUN
$result1->move(0); // move recordset cursor back to 0
while (!$result1->EOF) {
echo $result1->Fields('colname').'<br>';
$result2->MoveNext();
}

How to compare tables from different mySQL databases with PHP?

I'm new to PHP as well as the field and have been tasked with finding inconsistencies amongst tables from different mySQL databases. Every table should be the same between databases (column names, column count), with the exception of the actual data held in it, which they are not. I will need to identify the offending columns, the table they are in and, the database they are in. Below is my code thus far:
<?php
chdir(<path>);
include(<file>);
include(<file>);
$db = new db($hostname, $user, $pass, $commondatabase);
// Get baseline DB columns
//$db->select_db('<baseDB>');
//$btq = "SHOW TABLES";
//$btr = $db->query($btq);
//while($trows = $db->fetch_assoc($btr) {
// $bcq = "SHOW COLUMNS FROM ".$btr[<key>];
// $bcr = "$db->query($bcq);
// $basecolumns[] = $bcr;
//}
$dbq = "SELECT * FROM <commonDB>.<DBnames> ORDER BY <DBnamesID>";
$dbr = $db->query($dbq);
while($dbrow = $db->fetch_assoc($dbr)) {
echo "\n";
print_r($dbrow['dbname']);
echo "\n";
$db->select_db($dbrow['dbname']);
$tq = "SHOW TABLES";
$tr = $db->query($tq);
while($table = $db->fetch_assoc($tr)) {
/*print_r($dbtables);*/
$cq = "SHOW COLUMNS FROM ".$table['Tables_in_'.$dbrow['dbname']];
$cr = $db->query($cq);
$dbcols = [];
while($col = $db->fetch_assoc($cr)) {
/*print_r($col);*/ $dbcols = $col;
// Do check against baseline here
//if($dbcols != $basecolumns) {
// $badcolumns[] = $dbcols;
//}
}
}
}
$db->close();
?>
Currently it will loop down to the columns, but the output is not visually pleasing nor very manageable. My first concern is to get this working to where I can loop down to the columns and actually get them in their own arrays to be checked against the baseline and I've hit a wall, so any direction would be much appreciated. Currently each column is being assigned to its own array versus an array of all the column names for the database and table the loop is on. TIA!
Here is what I came up with. Not sure if it's the most DRY way to go about it, but it works and achieves the results I was looking for. Thank you to Barmar for sending me down the right path.
<?php
chdir(<path>);
include(<file>);
include(<file>);
$db = new db($hostname,$user,$pass,$commondatabase);
$db->select_db(<database>);
// Get tables from baseline database
$q="select distinct <column-name> from <table-name> where <where-param> ORDER BY <order-by-param>";
$r=$db->query($q);
while($tables=$db->fetch_assoc($r)) {
$table = $tables[<key>];
$x = array();
$x["$table"]=array();
// Get table columns from baseline database
$q="select <column-name> from <table-name> where <where-param> and <where-param> ORDER BY <order-by-param>";
$r2=$db->query($q);
while ($columns=$db->fetch_assoc($r2)) {
$x["$table"][]=$columns[<key>];
}
// Check other databases for this table
$q="select * from $commondatabase.<table-with-database-names> ";
$q.="where <where-param> order by <order-by-param>";
$r2=$db->query($q);
while ($databases=$db->fetch_assoc($r2)) {
$y = array();
$y["$table"]=array();
// Get table columns in $databases[<key>]
$q="select <column-name> from <table-name> where <where-param> and <where-param> ORDER BY <order-by-param>";
$r3=$db->query($q);
while ($columns=$db->fetch_assoc($r3)) {
$y["$table"][]=$columns[<key>];
}
// Check against baseline
$z1 = array_diff($x["$table"],$y["$table"]);
$z2 = array_diff($y["$table"],$x["$table"]);
// Echo out comparison results
if (empty($z1) && empty($z2)) {
//echo "all good.\n";
} else {
echo "Difference found in {$databases[<key>]}.{$tables[<key>]}:";
if (!empty($z1)) print_r($z1);
if (!empty($z2)) print_r($z2);
}
}
}
$db->close();
?>

How can I print a list of table names gathered by a certain prefix with MySqli and PHP

I am trying to retrieve a list of all tables inside my database with the prefix 'CMS_'
The Code I am working with right now is:
$DB->conn = new mysqli($DB->servername, $DB->username, $DB->password, $DB->database);
if(!$DB->conn->connect_errno){
$recordset = $DB->conn->query("SELECT * FROM `TABLES` WHERE TABLE_NAME LIKE 'CMS_*' AND TABLE_SCHEMA='$DB->database'");
if($recordset->num_rows < 1){echo ("<H2>You have no Content-Types Defined...</H2>");}
else{
$recordset = $recordset->fetch_array();
foreach($recordset as $record){
var_dump($record);echo "<BR/>";
}
}
}else{die("fatal error;no database connection;");}
In SQL You should use wildcard % instead of *
LIKE 'CMS_%'
EDIT:
while($record = $recordset->fetch_array()){
var_dump($record);echo "<BR/>";
}

DATE_FORMAT omit seconds

Trying to bring back a time id and time itself into listbox stored in mysql. run the sql in myadmin runs fine, try it in the code ... not so fine. bring back indefined index error.
thanks.
<?php
function get_times(&$a_class, &$db){
$str_sql =<<<EOT
SELECT timeId, DATE_FORMAT(tSel, '%H:%i')
FROM tb_time24
ORDER BY timeId
EOT;
if ($query_result = mysql_query($str_sql, $db)) {
while ($a_result = mysql_fetch_assoc($query_result)) {
$a = array();
$a['timeId'] = $a_result['timeId'];
$a['tSel'] = $a_result['tSel'];
array_push($a_class, $a);
}
}
else {
$i_result = mysql_errno($db);
}
if(isset($i_result)){
return $i_result;
}
}
?>
calling it here.
Start Time:<select name="startTime" id="StartTime">
<?php
$a_class = array();
get_times($a_class, $db_handle);
foreach ($a_class as $a_class) {
print "<option value='".$a_class['timeId']."'>{$a_class['tSel']}</option>\n";
}
?>
</select>
Give a name to the formatted column:
$str_sql =<<<EOT
SELECT timeId, DATE_FORMAT(tSel, '%H:%i') tSel
FROM tb_time24
ORDER BY timeId
EOT;
Otherwise the keys in the array returned by mysql_fetch_assoc would be timeId and DATE_FORMAT(tSel, '%H:%i').

PHP Problem with MySQL query. The function is only running for the first mysql result

I tried to search for something similar in the web but no results.
What I am trying to do is simply taking the results from the DATABASE and then run some functions for EACH result.
We have two kinds of functions.
The first function is when the row "Type" is = F , the second one when the row "Type" is = T.
The problem that I am having with this code is that it runs the functions ONLY for the first mySQL result.
But I have more results in the same time, and the functions should run for EACH mySQL result and not only for the first one.
I do not know if I need a foreach or whatever. I do not know anything about arrays and php loops.
Thank you.
include_once("../dbconnection.php");
date_default_timezone_set('UTC');
$TimeZone ="UTC";
$todaydate = date('Y-m-d') ."\n";
$time_utc=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('G:i:s',$time_utc);
$MembID =(int)$_COOKIE['Loggedin'];
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryMAIN="SELECT * FROM TableTuit WHERE TimeZone ='".$TimeZone."' AND Date ='".$todaydate."' ORDER BY ID ASC";
$result=mysql_query($queryMAIN) or die("Errore select TableT: ".mysql_error());
$tot=mysql_num_rows($result);
while($ris=mysql_fetch_array($result)){
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
if($time <= $NowisTime){
if($type=="F") //if the row type is = F, then do the things below
{
$queryF ="SELECT * FROM `TableF` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryF) or die("Errore select f: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0) {
$row = mysql_fetch_assoc($result);
DO FUNCTION // Should call the function that requires the above selected values from $queryF. Should Run this function for every mysql result given by $queryMAIN where row "type" is = F
}
}
}
if($type=="T") //if the row type is = T, then do the things below
{
$queryT = $queryF ="SELECT * FROM `TableT` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryT) or die("Errore select $queryT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count == 0)
$Isvalid = false;
else
{
$Isvalid = true;
$row = mysql_fetch_assoc($result);
}
if($Isvalid){
DO THIS FUNCTION // Should call the function that requires the above selected values from $queryT. Should Run this function for every mysql result given by $queryMAIN where row "type" is = T
}
}
}
}//END OF MYSQL WHILE OF $queryMAIN
You are using $result for the outer Query ($result=mysql_query($queryMAIN); and the Query inside the while loop $result=mysql_query($queryF); - I believe you do not want to mix these?
Right now you process the first row from TableTuit, then overwrite the $result with a row from TableF or TableT. In the next loop, the following columns will not be found in the array (unless they are also in these two tables, of course):
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
You are loading the results into an array, try using this in your while loop instead:
while($ris=mysql_fetch_assoc($result)){

Categories