I tried combining as suggested in a previous link but Im still getting a error. I am fairly new to php so that is why i have two querys.
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/vhockey/public_html/vhatest/connect.php on line 88
The table is "season12" and the table is "p"
Here is my connect.php file except server info...
function index_team_stats($subconference) {
$return = array();
$query = "SELECT id, teamname, teamnameseason, teamabr
FROM teams
WHERE subconference = '" . $subconference . "'
ORDER BY teamnameseason";
$teams = result_array($query);
foreach ($teams as $team)
{
$query = "SELECT gp, w, l, ol, p
FROM season12
WHERE team = '" . $team['teamnameseason'] . "'
ORDER BY p DESC
LIMIT 0,20'; ";
$results = result_array($query);
if ($results)
{
$results[0]['team'] = str_replace($team['teamnameseason'], '', $team['teamname']);
$results[0]['teamabr'] = $team['teamabr'];
$results[0]['teamid'] = $team['id'];
$return[] = $results[0];
}
}
return $return;
}
function get_team_name($teamnameseason) {
$query = "SELECT teamname FROM teams WHERE teamnameseason = '" . $teamnameseason . "'";
$row = mysql_fetch_row(mysql_query($query));
return str_replace($teamnameseason, '', $row[0]);
}
function result_array($query) {
$results = mysql_query($query) or die("error on: " . $query . " saying: " . mysql_error());
$return = array();
while ($row = mysql_fetch_assoc($results)) {
$return[] = $row;
}
return $return;
}
Here is an image of the info ![All info sorted by team PTS from highest to lowest
Should show Penguins, FLyers, Islanders, Rangers, Devils..
Use a JOIN. An example is below. You may need to tweak based on your specific needs.
SELECT teams.id, teams.teamname, teams.teamnameseason, teams.teamabr, season12.gp,
season12.w, season12.l, season12.ol, season12.p
FROM teams, season12
INNER JOIN season12
ON teams.teamname=season12.team
WHERE teams.subconference = '$subconference'
ORDER BY season12.p
LIMIT 0,20
Please note this code is not tested and may require modification.
You can use php sort function http://php.net/usort
$callback = new function ($el1, $el2) {
if ($el1['points'] == $el2['points']) {
return 0;
}
return ($el1['points'] < $el2['points']) ? -1 : 1;
}
$sorted_result = usort($results, $callback);
Related
I want to create a script. The script will automatically list random firstname and lastname.
There are two database tables.
First: fake_name_id, fake_firstname
Second:fake_name_id,fake_lastname
So far I have made this:
controller file
$data['lastname'] = array();
$results = $this->getRandomLastNames();
foreach ($results as $result) {
$data['lastname'][] = array(
'lastname' => $result['lastname'],
);
}
$data['fullnames'] = array();
$results = $this->getRandomNames();
foreach ($results as $result) {
$data['fullnames'][] = array(
'firstname' => $result['firstname'],
);
}
model file >>>>> sql query firstname and lastname
public function getRandomName($fake_name_id) {
$query = $this->db->query("SELECT DISTINCT *, fake_firstname FROM " . DB_PREFIX . " fakereviews_name WHERE fake_name_id = '" . (int)$fake_name_id . "'");
if ($query->num_rows) {
return array(
'fake_name_id' => $query->row['fake_name_id'],
'firstname' => $query->row['fake_firstname'],
);
} else {
return false;
}
}
public function getRandomNames($data = array()) {
$sql = "SELECT * FROM " . DB_PREFIX . "fakereviews_name ORDER BY Rand() ASC LIMIT 0, 20";
$fake_firstname_data = array();
$query = $this->db->query($sql);
foreach ($query->rows as $result) {
$fake_firstname_data[$result['fake_name_id']] = $this->getRandomName($result['fake_name_id']);
}
return $fake_firstname_data;
}
public function getRandomLastName($fake_name_id) {
$query = $this->db->query("SELECT DISTINCT *, fake_lastname FROM " . DB_PREFIX . " fakereviews_lastname WHERE fake_name_id = '" . (int)$fake_name_id . "'");
if ($query->num_rows) {
return array(
'fake_name_id' => $query->row['fake_name_id'],
'lastname' => $query->row['fake_lastname'],
);
} else {
return false;
}
}
public function getRandomLastNames($data = array()) {
$sql = "SELECT * FROM " . DB_PREFIX . "fakereviews_lastname ORDER BY Rand() ASC LIMIT 0, 20";
$fake_lastname_data = array();
$query = $this->db->query($sql);
foreach ($query->rows as $result) {
$fake_lastname_data[$result['fake_name_id']] = $this->getRandomLastName($result['fake_name_id']);
}
return $fake_lastname_data;
}
twig file
{% for fullname in fullnames %}
{{ fullname['firstname'] }} {{ fullname['lastname'] }}
{% endfor %}
When the page loads. well creates 20 pieces of firstname.
But I can't get it to display lastname correctly.
Please help me to create foreach random fullname (first and last name) with predefined quantity.
You can simply use rand() function.
Create an array of fake_firstname and one for fake_lastname and then join them using a loop, wrap everything inside a function and you have what you need.
say you need an array of $n fake names
Example pseudocode:
public function randomNames($n){
// $first_name_array = fetch all first names in an array;
// $last_name_array = fetch all last names in an array;
$random_names = [];
foreach($n as $i){
$random_full_name = $first_name_array[rand(0,$n)%count($first_name_array)].' '.$last_name_array[rand(0,$n)%count($last_name_array)];
array_push($random_names,$random_full_name);
}
return($random_names);
}
I am having a huge issue looping through results, These two queries work hand in hand to check if a restaurant is open today. My problem is i have restaurants, id 1-5(more in the future). But the loop seems to only get restaurant id 5. I have read many posts on here and it seems like i am doing the right thing. But i cannot seem to loop to get the other restaurant id's.
I am blocked now, newbie who is very open to any suggestions or advise.
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++;
}
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
You could either output whatever you want to within your loop or build-up an output string because the value of $rest_ will always be the last value in the loop and i don't think that's what you want... Again you are doing the same with $message. And I am willing to bet that this is what you want to do:
<?php
date_default_timezone_set("Europe/London");
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++; // <== YOU DON'T NEED THIS VARIABLE....
// GET THE DATES WITHIN THE LOOP...
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
}
I think this is what you are trying to do.
// $searchP should be checked to prevent SQL injection.
$sel = "SELECT Rest_Details.Resturant_ID, Delivery_Pcode.Pcode,
Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID = Rest_Details.Resturant_IDW
WHERE Delivery_Pcode.Pcode LIKE '$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
// set these once as they don't change
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
// $i=1; - not required, never used
// loop over the original results
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
//$i++; not used
// check for a match
$query = "SELECT * FROM Opening_hrs
WHERE Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
// at least one match
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "<br />";
$message .= "close" . $row_qu["Closing_time"] . "<br />";
}
} else {
// no matches
$message = "No results for <i>$daynum</i>.";
}
}
It should be possible to get the details in a single query, but I would need to see your SQL tables for that (and you did not ask for that too :]).
Also, it is <br> or <br />, not </br>.
I am a complete noob in php and trying to learn it by working on a premade script and making changes to it. I have been trying to figure out how to display titles by their first letters in a table. I went through this site http://www.emirplicanic.com/php/php-a-to-z-sorting-script but wasn't able to make it work in the script.
public function getProducts()
{
global $db, $core, $pager;
require_once(BASEPATH . "lib/class_paginate.php");
$pager = new Paginator();
$pager = new Paginator();
$counter = countEntries($this->pTable);
$pager->items_total = $counter;
$pager->default_ipp = $core->perpage;
$pager->paginate();
if ($counter == 0) {
$pager->limit = "";
}
if (isset($_GET['sort'])) {
list($sort, $order) = explode("-", $_GET['sort']);
$sort = sanitize($sort);
$order = sanitize($order);
if (in_array($sort, array("title", "cid", "price", "created"))) {
$ord = ($order == 'DESC') ? " DESC" : " ASC";
$sorting = " p." . $sort . $ord;
} else {
$sorting = " p.created DESC";
}
} else {
$sorting = " p.created DESC";
}
----------added by me-----------------
if (isset($_GET['letter'])) {
list($letter, $order1) = explode("-", $_GET['letter']);
$letter = sanitize($letter);
$order1 = sanitize($order1);
// if (in_array($sort, "A", "B", "C", "D"))) {
if (!(strcmp($letter, "A"))) {
$ord1 = ($order1 == 'DESC') ? " DESC" : " ASC";
$sorting1 = " p." . $letter . $ord1;
}
}
------------------------------------------------------------------
$sql = "SELECT p.*, p.id as pid, c.name, c.id as cid,"
. "\n DATE_FORMAT(p.created, '" . $core->short_date . "') as cdate,"
. "\n (SELECT COUNT(pid) FROM transactions WHERE pid = p.id) as sales"
. "\n FROM " . $this->pTable . " as p"
. "\n LEFT JOIN categories as c ON c.id = p.cid"
. "\n ORDER BY " . $sorting . $pager->limit;
$row = $db->fetch_all($sql);
return ($row) ? $row : 0;
}
and then the html part of it is
<li><span>A</span></li>
<li><span>B</span></li>
.
.
.
The php part is giving me an Undefined offset error. Also i am not sure if i have to add anything extra on the html to make it work
The URLS in your HTML should be ?letter=A-DESC. (or ASC) The list($letter, $order1) is expecting two results from the call to explode('-', $_GET['letter']), and it's only getting one. Thus, an 'undefined offset' in the array returned from explode().
Note that anyone can send anything in the ?letter part of the URL, not just what's in your links. You should "sanitize" (whatever that does for you) any input arguments as the very first step, and handle the situation where the data isn't what you expect before you start processing that data.
I have a database containing three tables:
practices - 8 fields
patients - 47 fields
exacerbations - 11 fields
The majority of the fields in these tables are recorded in varchar format, other fields include integers, doubles and dates.
I have to transform this data into numerically classified data so that it can be used by a statistician to extrapolate any patterns in the data. To acheive this I will have to convert varchar fields into integers that represent the classification that string belongs to, an example being 'Severity' which has the following possible string values:
Mild
Moderate
Severe
Very Severe
This field in the patients table has a finite list of string values that can appear, other fields have an endless possibility of string values that cannot be classified until they are encountered by my database (unless I implement some form of intelligent approach).
For the time being I am just trying to construct the best approach to converting each field for all entries in each of the 3 tables to numeric values. The pseudo code I have in my head so far is as follows (it's not complete):
function profileDatabase
for each table in database
for each field that is of type varchar
select all distinct values and insert into classfication table for that field
end for
end for
function classifyDatabase
for each table in database
for each field that is of type varchar
// do something efficient to build an insert string to place into new table
end for
end for
Can someone suggest the best way of performing this process so that it is efficient giving that there are currently in excess of 100 practices, 15,000 patients and 55,000 exacerbations in the system. I have no need to implement this in PHP, build I would prefer to do so. Any pointers as to how to structure this would be great as I am not sure my approach the best approach.
This process will have to run every month for the next two years as the database grows to have a total of 100,000 patients.
Maybe http://dev.mysql.com/doc/refman/5.1/en/procedure-analyse.html will help to get an overview to find out how fields are used.
I have managed to build my own solution to this problem which runs in reasonable time. For anyone interested, or anyone who may encounter a similar issue here is the approach I have used:
A PHP script that is run as a cron job by calling php scriptName.php [database-name]. The script builds a classified table for each table name that is within the database (that is not a lookup table for this process). The setting up of each classification creates a new table which mimics the format of the base table but sets all fields to allow NULL values. It then creates blank rows for each of the rows found in the base table. The process then proceeds by analysing each table field by field and updating each row with the correct class for this field.
I am sure I can optimise this function to improve on the current complexity, but for now I shall use this approach until the run-time of the scripts goes outside of an acceptable range.
Script code:
include ("../application.php");
profileDatabase("coco");
classifyDatabase("coco");
function profileDatabase($database) {
mysql_select_db($database);
$query = "SHOW TABLES";
$result = db_query($query);
$dbProfile = array();
while ($obj = mysql_fetch_array($result)) {
if (!preg_match("/_/", $obj[0])) {
$dbProfile[$obj[0]] = profileTable($obj[0]);
}
}
return $dbProfile;
}
function profileTable($table) {
$tblProfile = array();
$query = "DESCRIBE $table";
$result = db_query($query);
while ($obj = mysql_fetch_array($result)) {
$type = substr($obj[1], 0, 7);
//echo $type;
if (preg_match("/varchar/", $obj[1]) && (!preg_match("/Id/", $obj[0]) && !preg_match("/date/", $obj[0]) && !preg_match("/dob/", $obj[0]))) {
$x = createLookup($obj[0], $table);
$arr = array($obj[0], $x);
$tblProfile[] = $arr;
}
}
return $tblProfile;
}
function getDistinctValues($field, $table) {
$distinct = array();
$query = "SELECT DISTINCT $field as 'value', COUNT($field) as 'no' FROM $table GROUP BY $field ORDER BY no DESC";
$result = db_query($query);
while ($obj = mysql_fetch_array($result)) {
$distinct[] = $obj;
}
return $distinct;
}
function createLookup($field, $table) {
$query = "CREATE TABLE IF NOT EXISTS `" . $table . "_" . $field . "`
(
`id` int(5) NOT NULL auto_increment,
`value` varchar(255) NOT NULL,
`no` int(5) NOT NULL,
`map1` int(3) NOT NULL,
`map2` int(3) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1";
db_query($query);
$distinct = getDistinctValues($field, $table);
$count = count($distinct);
foreach ($distinct as $val) {
$val['value'] = addslashes($val['value']);
$rs = db_query("SELECT id FROM " . $table . "_" . $field . " WHERE value = '" . $val['value'] . "' LIMIT 1");
if (mysql_num_rows($rs) == 0) {
$sql = "INSERT INTO " . $table . "_" . $field . " (value,no) VALUES ('" . $val['value'] . "', " . $val['no'] . ")";
} else {
$sql = "UPDATE " . $table . "_" . $field . " (value,no) VALUES ('" . $val['value'] . "', " . $val['no'] . ")";
}
db_query($sql);
}
return $count;
}
function classifyDatabase($database) {
mysql_select_db($database);
$query = "SHOW TABLES";
$result = db_query($query);
$dbProfile = array();
while ($obj = mysql_fetch_array($result)) {
if (!preg_match("/_/", $obj[0])) {
classifyTable($obj[0]);
//echo "Classfied $obj[0]\n";
}
}
}
function classifyTable($table) {
$query = "SHOW TABLES";
$result = db_query($query);
$dbProfile = array();
$setup = true;
while ($obj = mysql_fetch_array($result)) {
if ($obj[0] == "classify_" . $table)
$setup = false;
}
if ($setup) {
setupClassifyTable($table);
//echo "Setup $table\n";
}
$query = "DESCRIBE $table";
$result = db_query($query);
while ($obj = mysql_fetch_array($result)) {
if (preg_match("/varchar/", $obj[1]) && (!preg_match("/Id/", $obj[0]) && !preg_match("/date/", $obj[0]) && !preg_match("/dob/", $obj[0]))) {
$rs = db_query("
SELECT t.entryId, t.$obj[0], COALESCE(tc.map1,99) as 'group' FROM $table t
LEFT JOIN " . $table . "_$obj[0] tc ON t.$obj[0] = tc.value
ORDER BY tc.map1 ASC");
while ($obj2 = mysql_fetch_object($rs)) {
$sql = "UPDATE classify_$table SET $obj[0] = $obj2->group WHERE entryId = $obj2->entryId";
db_query($sql);
}
} else {
if ($obj[0] != "entryId") {
$rs = db_query("
SELECT t.entryId, t.$obj[0] as 'value' FROM $table t");
while ($obj2 = mysql_fetch_object($rs)) {
$sql = "UPDATE classify_$table SET $obj[0] = '" . addslashes($obj2->value) . "' WHERE entryId = $obj2->entryId";
db_query($sql);
}
}
}
}
}
function setupClassifyTable($table) {
$tblProfile = array();
$query = "DESCRIBE $table";
$result = db_query($query);
$create = "CREATE TABLE IF NOT EXISTS `classify_$table` (";
while ($obj = mysql_fetch_array($result)) {
if (preg_match("/varchar/", $obj[1]) && (!preg_match("/Id/", $obj[0]) && !preg_match("/date/", $obj[0]) && !preg_match("/dob/", $obj[0]))) {
//echo $obj[1]. " matches<br/>";
$create .= "$obj[0] int(3) NULL,";
} else {
$create .= "$obj[0] $obj[1] NULL,";
}
}
$create .= "PRIMARY KEY(`entryId`)) ENGINE=MyISAM DEFAULT CHARSET=latin1";
db_query($create);
$result = mysql_query("SELECT entryId FROM $table");
while ($obj = mysql_fetch_object($result)) {
db_query("INSERT IGNORE INTO classify_$table (entryId) VALUES ($obj->entryId)");
}
}
?>
I'm attempting the modify this Modx Snippet so that it will accept multiple values being returned from the db instead of the default one.
tvTags, by default, was only meant to be set to one variable. I modified it a bit so that it's exploded into a list of variables. I'd like to query the database for each of these variables and return the tags associated with each. However, I'm having difficulty as I'm fairly new to SQL and PHP.
I plugged in $region and it works, but I'm not really sure how to add in more WHERE clauses for the $countries variable.
Thanks for your help!
if (!function_exists('getTags')) {
function getTags($cIDs, $tvTags, $days) {
global $modx, $parent;
$docTags = array ();
$baspath= $modx->config["base_path"] . "manager/includes";
include_once $baspath . "/tmplvars.format.inc.php";
include_once $baspath . "/tmplvars.commands.inc.php";
if ($days > 0) {
$pub_date = mktime() - $days*24*60*60;
} else {
$pub_date = 0;
}
list($region, $countries) = explode(",", $tvTags);
$tb1 = $modx->getFullTableName("site_tmplvar_contentvalues");
$tb2 = $modx->getFullTableName("site_tmplvars");
$tb_content = $modx->getFullTableName("site_content");
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
$rs = $modx->db->query($query);
$tot = $modx->db->getRecordCount($rs);
$resourceArray = array();
for($i=0;$i<$tot;$i++) {
$row = #$modx->fetchRow($rs);
$docTags[$row['contentid']]['tags'] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
}
if ($tot != count($cIDs)) {
$query = "SELECT name,type,display,display_params,default_text";
$query .= " FROM $tb2";
$query .= " WHERE name='".$region."' LIMIT 1";
$rs = $modx->db->query($query);
$row = #$modx->fetchRow($rs);
$defaultOutput = getTVDisplayFormat($row['name'], $row['default_text'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
foreach ($cIDs as $id) {
if (!isset($docTags[$id]['tags'])) {
$docTags[$id]['tags'] = $defaultOutput;
}
}
}
return $docTags;
}
}
You don't add in more WHERE clauses, you use ANDs and ORs in the already existing where clause. I would say after the line $query .= " WHERE stv.name = '".$region... you put in
foreach ($countries as $country)
{
$query .= "OR stv.name = '{$country}', ";
}
but I don't know how you want the query to work.