I am wondering how to do the following I want to create a public function that allows me to do selects from MYSQL
Here is the code I have so far but it brings up a if error.
public function select($table,$options,$where,$orderby)
{
$sql = mysql_query("SELECT ".
if($options)
{
$options
}
." FROM ".
$table
if($where)
{
." WHERE ".$where.
}
if ($orderby)
{
." ORDER BY ".$orderby.
}
."") or mysql_error() ;
$row = mysql_fetch_assoc($sql);
$rows[] = $row;
print json_encode($rows);
}
Parse error: syntax error, unexpected T_IF in /home/realcas/public_html/eshop/ecms/system/classes/database.php on line 23
Try
$sql = mysql_query("SELECT ". $options ." FROM ". $table .
($where ? "WHERE " . $where : "") .
($orderby? "ORDER BY ".$orderby : "")) or mysql_error() ;
$row = mysql_fetch_assoc($sql);
$rows[] = $row;
print json_encode($rows);
You cannot have if-statements inside a function call. Build your SQL outside and then pass it directly to mysql_query. Example:
$sql = "SELECT ";
if($options)
$sql .= "FROM " . $table;
if($where)
$sql .= " WHERE " . $where;
if($orderby)
$sql .= " ORDER BY " . $orderby;
$query = mysql_query($sql);
I also assume that you're missing an exit before mysql_error(). As it is now, you wont get any output. Change it to:
mysql_query($sql) or die(mysql_error());
Third, you will only be able to fetch a single row since you only invoke mysql_fetch_assoc once. You should continue iterating over it as long as there are results:
$rows = array();
while($row = mysql_fetch_assoc($query))
$rows[] = $row;
// $rows will now contain all rows returned from your select statement
enhanced way:
public function select($table,$options,$where,$orderby)
{
$options = empty($options) ? "*" : $options;
$where = empty($where) ? "1=1" : $where;
$orderby = empty($orderby) ? "" : $orderby;
$qry = "SELECT $options FROM $table WHERE $where $orderby ";
$result= mysql_query($qry) or die(mysql_error());
while(($resultArray[] = mysql_fetch_assoc($result));
return json_encode($resultArray);
}
Related
i have little problem here, i want to generate some data to specific JSON format from Mysql using PHP, this is my PHP code
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
// echo(json_encode($names));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
?>
With this code, the result was
[
[1478616679000, 1478616677000, 1478616675000, 1478616673000, 1478616671000],
[28.4126, 28.5361, 28.4126, 28.4126, 28.2891]
]
Yes, that is valid JSON but, i want to use this JSON for chart in highcharts.com, so i need the JSON format like this
[
[1257811200000, 29.00],
[1257897600000, 29.04],
[1257984000000, 28.86],
[1258070400000, 29.21],
[1258329600000, 29.52],
[1258416000000, 29.57],
[1258502400000, 29.42],
[1258588800000, 28.64],
[1258675200000, 28.56],
[1258934400000, 29.41],
[1259020800000, 29.21],
[1259107200000, 29.17],
[1259280000000, 28.66],
[1259539200000, 28.56]
]
Gladly if someone can help me, i'm stuck for a days try to solving this issue
If you want the code like that, you must fix the code:
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
must be something like this:
while($row = $result->fetch_array()){
$rows[] = array(
(float)$row['ai0_hist_value'],
strtotime($row['meas_date'])*1000);
}
echo (json_encode($rows));
You were saving in $data2 an array with two arrays, the text and the data. You must save a row for each pair of 'text' and 'data'.
Could construct the formatted series data to begin with like below:
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$seriesData[] = [ strtotime($row['meas_date'])*1000, (float)$row['ai0_hist_value'] ];
}
echo (json_encode($seriesData));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
This will generate the array you want, there is no need to do all that fiddling with the data from the database
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
$rows = array();
if ($result = $db->query($sql)) {
while($row = $result->fetch_array()){
$rows[] = array(strtotime($row['meas_date'])*1000,
$row['ai0_hist_value']
);
}
}
echo json_encode($rows);
Now you will need to convert the text to float in the javascript. This is because JSON is passed as text and not any other data type, so it has to be converted, if necessary in the receiving javascript.
Need to pass through an argument for column header in to function.
Would like to have ["name"] be an argument in the function so I can pull different fields from sql, Can you please help. Thank you.
Here is the function:
function read_pages_array_2 () {
global $connection;
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "ORDER BY id ASC";
$result = mysqli_query ($connection, $query);
confirm_query ($result);
while($result_use = mysqli_fetch_assoc($result)) {
echo $result_use["name"] . "<br/>";
}
}
function read_pages_array_2($columnName) {
global $connection;
$query = "SELECT p.".$columnName." FROM pages p ORDER BY id ASC";
$result = $connection->query($query); // Object Oriented use of connection
confirm_query($result);
while ($result_use = $result->fetch_assoc()) {
echo $result_use[$columnName] . "<br/>";
}
Yes?
OP asked
Looking for ["name"] to be an argument, so I can change when using
function and instead of name, get ["page_id"] or whatever else.
function read_pages_array_2 ($param) {
global $connection;
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "ORDER BY id ASC";
$result = mysqli_query ($connection, $query);
confirm_query ($result);
while($result_use = mysqli_fetch_assoc($result)) {
echo $result_use[$param] . "<br/>";
}
}
read_pages_array_2("name");
read_pages_array_2("pageID");
Isn't this straight forward?
I am creating search query in php by passing variable through GET method. When the variable is null then it's passing the query like,
SELECT * FROM table WHERE column_name = null.
And it's showing error (obvious). I want to create query like. If user don't select anything from search options then it should fetch all the data from that column.
What's the correct logic for that?
Thanks.
Code:
if(isset($_GET['selPetType']) && $_GET['selPetType'] != '')
{
$searchParams['petType'] = $_GET['selPetType'];
$queryStr .= " PetType='" .$_GET['selPetType']. "'";
}
if(isset($_GET['txtPetBreed1']) && !empty($_GET['txtPetBreed1']))
{
$searchParams['breed'] = $_GET['txtPetBreed1'];
$queryStr .= " AND PetBreed1 ='". $_GET['txtPetBreed1'] . "'";
}
$clause1 = "SELECT * FROM pet WHERE $queryStr ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit";
$totalRun1 = $allQuery->run($clause1);
Maybe something like this:
$get['param1'] = 'foo';
$get['param3'] = null;
$get['param2'] = '';
$get['param4'] = 'bar';
$where = null;
foreach ($get as $col => $val) {
if (!empty($val)) {
$where[] = $col . ' = "' . $val . '"';
}
}
$select = 'SELECT * FROM pet ';
if ($where) {
$select .= 'WHERE ' . implode(' AND ', $where);
}
$select .= ' ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit';
Edit: I added if to remove empty values and added 2 new values to example so you can see this values will not be in query.
if(isset($_GET['your_variable'])){
$whr = "column_name = $_GET['your_variable']";
}
else{
$whr = "1 = 1";
}
$qry ="SELECT * FROM table WHERE ".$whr;
For example :
<?php
$userSelectedValue = ...;
$whereCondition = $userSelectedValue ? " AND column_name = " . $userSelectedValue : "" ;
$query = "SELECT * FROM table WHERE 1" . $whereCondition;
?>
Then consider it's more safe to use prepared statements.
function getDepartmentAndCondition($dep, $userid, $cond) {
$result = mysql_query("SELECT * FROM department WHERE ID='$dep'");
while($row = mysql_fetch_array($result))
{
$DepConInfo['Department'] = $row['Department'];
}
$userName = mysql_query("SELECT * FROM users WHERE FacebookID = '$userid'") or die ("<hr>error in SQL query: " . mysql_error() . "<hr>");
while($row = mysql_fetch_array($username)) {
$DepConInfo['Name'] = $row['name'];
}
$result2 = mysql_query("SELECT * FROM condition WHERE ID= '$cond' ")
or die("<hr>error in SQL query: " . mysql_error() . "<hr>");
while($row2 = mysql_fetch_array($result2))
{
$DepConInfo['Condition'] = $row2['Condition'];
}
return $DepConInfo;
}
$dep, $userid, and $cond are all ints. the first one $DepConInfo['Department'] is returning the right string, but the other two fail with the error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in ...
ok I rewrote the function
function getCondition($cond) {
$query = "SELECT * FROM condition WHERE ID = '$cond' ";
$sql = mysql_query($query);
if (!$sql) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row2 = mysql_fetch_array($sql))
{
$condition = $row2['Name'];
}
return $condition;
}
but I'm still getting an error:
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition WHERE id = '1'' at line 1 Whole query: SELECT * FROM condition WHERE ID = '1'
the table "condition" has two columns "ID" and "Name".
while($row = mysql_fetch_array($username)) {
PHP is case-sensitive: you have $username with wrong caps - should be $userName
Additionally, based on your naming convention in the first and third queries
$DepConInfo['Name'] = $row['name'];
is probably incorrect and should be capitalized as $row['Name']
function getDepartment($dep) {
$sql = "SELECT * FROM department WHERE ID = '$dep'";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$department = $row['Department'];
}
return $department;
}
function getName($userid) {
$sql = "SELECT * FROM users WHERE FacebookID = '$userid'";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$user_name = $row['Name'];
}
return $username;
}
function getCondition($cond) {
$sql = "SELECT * FROM condition WHERE id = '$cond'";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$condition = $row['Condition'];
}
return $condition;
}
$department = getDepartment($dep);
$username = getName($userid);
$condition = getCondition($cond);
I'm writing this from my head so I did not test it, but it should work or at least get you on your way. If not let me know. Mind capitalization using caps in your dbase table and column names can make things more confusing. Use $sql to store your query, use $result to store the result. This is more descriptive. Good luck!
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.