I'm trying out to use joomla to do my query code. But there is some error code shown that my courseID is in array and can't be use. Sorry i was still new to joomla and php >.<
Here is my code:
$campusID = $_POST['campusID'];
$courseID = $_POST['courseID'];
$from= $_POST['from'];
$to= $_POST['to'];
// Get default database object
$db =JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
foreach($courseID as $courseID1){
// Build the query
$query->select($db->quoteName('startdate'));
$query->from($db->quoteName('intake'));
$query->where($db->quoteName('campusid').'='. $db->quote($campusID));
$query->where($db->quoteName('courseid').'='. $db->quote($courseID1));
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($result){
echo "GOOD";
}
else{
echo "Error";
}
}
Eventually, $courseID is the value that i submitted from another page which the value is come from a check box and carry multiple value. What should i do to get the courseID value with array in query? ( I had try to edit the code, but no luck...it still echo me "Error".
By default
$query->where($condition)
appends conditions using an AND when you use several where's. So your code will produce something like
campusid = XX AND courseid = YY AND campusid = XX AND courseid = ZZ ...
So it doesn't work because courseid cannot be YY and ZZ at the same time.
You use a trick to solve this, using explode but before exploding, we must sanitize the received data.
This code is not tested :
$tmpIds = array();
foreach($courseID as $cId){
$tmpIds[] = $db->quote($cId); // sanitize the input
}
$courseID1 = explode($tmpIds,",");
$query->select($db->quoteName('startdate'));
$query->from($db->quoteName('intake'));
$query->where($db->quoteName('campusid').'='. $db->quote($campusID));
$query->where($db->quoteName('courseid').' IN ('. $courseID1 . ')';
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($result){
echo "GOOD";
} else {
echo "Error";
}
As pointed on the notes below, you should avoid using $_POST, $_GET, $_FILES, etc... directly. Since Joomla! 2.5 JInput class (on 1.5 to 1.7 this was done with JRequest) is provided to access those variables.
Regards,
Related
So I am using this tutorial: https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/ to try and get data from my local MYSQL server (using Wamp64). I had the undefined index error at first, which I fixed using the isset() statement.
But now it just returns:
{"result":[]}
I have, however, a lot of data in the set column of that database.
Here is the code:
<?php
//Getting the requested klas
$klas = isset($_GET['klas']) ? $_GET['klas'] : '';
//Importing database
require_once('dbConnect.php');
//Creating SQL query with where clause to get a specific klas
$sql = "SELECT * FROM lessen WHERE klas='$klas'";
//Getting result
$r = mysqli_query($con,$sql);
//Pushing result to an array
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
//Displaying the array in JSON format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I tried out the
SELECT * FROM lessen WHERE klas='$klas'
statement in my database and it seems to return the correct data.
Any idea what is causing this?
Thanks in advance!
Point 1 is:
isset function only checks if klas is set in the $_GET global array. So if somehow $klas is blank - your query will return empty (without giving error).
So please check values in the $_GET and possibly from where it is accessed. Or you can add condition to avoid empty query like --
if (!empty($_GET['klas'])) {
// rest of the code block upto return
Point 2 is:
You have mentioned if you echo the sql it returns
SELECT * FROM lessen WHERE klas=''{"result":[]}
Here the second part (the JSON) is from echoing the result at the end of your code. So for the first part (i.e. echoing $sql) we see that klas=''. That actually goes to the Point 1 as mentioned above.
So finally you have to check why the value at $_GET is showing blank. That will solve your problem.
UPDATE:
From #GeeSplit's comment For the request
"GET /JSON-parsing/getKlas.php?=3ECA"
There will be nothing in $_GET['klas'] cause the querystring in the url doesn't contain any key.
So either you have to change the source from where the file is called. Or you can change how you are getting the value of klas.
Example:
$tmpKlas = $_SERVER['QUERY_STRING'];
$klas = ltrim($tmpKlas, '=');
Rest of your code will work.
Use this code
<?php
$klas ='';
if(isset($_GET['klas']) && !empty($_GET['klas']))
{
$klas = $_GET['klas'];
require_once('dbConnect.php');
$sql = 'SELECT * FROM lessen WHERE klas="'.$klas.'"';
$r = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
?>
I'm new to joomla jdatabase. Currently I having a error code on my query in joomla which I using sourcerer plugin to insert the code.
Here is my code:
$campusID = $_POST['campusID'];
$courseID = $_POST['courseID'];
// Get default database object
$db =JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
$tmpIds = array();
foreach($courseID as $cId){
$tmpIds = $db->quote($cId); //sanitize the input
}
$courseID1 = explode($tmpIds, ",");
// Build the query
$query->select($db->quoteName('courseid'));
$query->from($db->quoteName('intake'));
$query->where($db->quoteName('campusid').'='. $db->quote($campusID));
$query->where($db->quoteName('courseid').'IN('.$courseID1.')');
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($results){
echo 'Good';
}
else{ echo 'Error';}
Apparently, the courseID is an array that post by other form and it was using a check box. But somehow maybe my logic thinking is bad, I couldn't found anyway to compare the courseID with the database courseID to determine whether the courseID is existing in the database or not, else it might just prompt the error message.
Here is what error message I get from joomla when I am trying to execute it.
Error 1054. Unknown column 'Array' in 'where clause' SQL=SELECT `courseid` FROM `intake` WHERE `campusid`='Campus2' AND `courseid`IN(Array)
Try this
first of all you have a change of
$tmpIds = $db->quote($cId);
To
$tmpIds[] = $db->quote($cId);
after you want to use a implode()
$courseID1 = explode($tmpIds, ",");
To
$courseID1 = implode(',',$tmpIds);
I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows
I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);
I have a select statement where I want to get all rows from a table but seem to be having a mental blockage - this should be elementary stuff but can't seem to get it working.
There are only two rows in the table 'postage_price' - and two columns : price | ref
Select statement is as follows:
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[]=$post_row;
}
I am then trying to echo the results out:
echo $post1['0'];
echo $post1['1'];
this is not showing anything. My headache doesn't help either.
while($post_row = mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[] = $post_row['price'];
}
As you see: $post_row in this line: = mysqli_fetch_array($dbc, $get_postage_result) is an array. You are trying to save the whole array value to another array in a block. :)
EDIT
while($post_row = mysqli_fetch_array($get_postage_result))
...
You have $post1[]=$post_row; and $post_row is itself an array. So you can access post data with following: $post1[NUMBER][0] where NUMBER is a $post1 array index and [0] is 0-index of $post_row returned by mysqli_fetch_array.
Probably you wanted to use $post1[]=$post_row[0]; in your code to avoid having array of arrays.
You are passing 1 and 0 as string indexes, this would only work if you had a column called 0 or 1 in you database. You need to pass them as numeric indexes.
Try:
print_r($post1[0]);
print_r($post1[1]);
or
print_r($post['price']);
print_r($post['ref']);
with all your help I have found the error - it is in the mysqli_fetch_array where I had the $dbc which is not required.
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($get_postage_result))
{
$post1[]=$post_row['price'];
}
instead of:
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[]=$post_row['price'];
}
Bad day for me :(
Thanks all
If something does not work in a PHP script, first thing you can do is to gain more knowledge. You have written that
echo $post1['0'];
echo $post1['1'];
Is showing nothing. That could only be the case if those values are NULL, FALSE or an empty string.
So next step would be to either look into $post1 first
var_dump($post1);
by dumping the variable.
The other step is that you enable error display and reporting to the highest level on top of your script so you get into the know where potential issues are:
ini_set('display_errors', 1); error_reporting(~0);
Also you could use PHP 5.4 (the first part works with the old current PHP 5.3 as well, the foreach does not but you could make query() return something that does) and simplify your script a little, like so:
class MyDB extends mysqli
{
private $throwOnError = true; # That is the die() style you do.
public function query($query, $resultmode = MYSQLI_STORE_RESULT) {
$result = parent::query($query, $resultmode);
if (!$result && $this->throwOnError) {
throw new RuntimeException(sprintf('Query "%s" failed: (#%d) %s', $query, $this->errno, $this->error));
}
return $result;
}
}
$connection = new MyDB('localhost', 'testuser', 'test', 'test');
$query = 'SELECT `option` FROM config';
$result = $connection->query($query);
foreach ($result as $row) {
var_dump($row);
}