Joomla Query Array Error - php

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);

Related

MySQL UPDATE Not Updating any row

What's wrong with the following syntax:
if( isset($_POST['save_changes']) ) {
// Get current id of customer
$currentID = $_GET['id'];
// Get Input Values
$newfirstName = validateInputData($_POST['first_name']);
$newlastName = validateInputData($_POST['last_name']);
$newemail = validateInputData($_POST['email']);
$newphone = validateInputData($_POST['phone_number']);
$newaddressOne = validateInputData($_POST['address_one']);
$newaddressTwo = validateInputData($_POST['address_two']);
$newcounty = validateInputData($_POST['county']);
$newcity = validateInputData($_POST['city']);
$newzipCode = validateInputData($_POST['zip_code']);
$newprovince = validateInputData($_POST['province']);
$newstate = validateInputData($_POST['state']);
// Queries
$query = "UPDATE customers
SET
first_name='$newfirstName',
last_name='$newlastName',
email='$newemail',
phone='$newphone'
WHERE id='$currentID'
";
$conn->query($query) or die($conn->error.__LINE__);
$query = "UPDATE addresses
SET
address_one='$newaddressOne',
address_two='$newaddressTwo',
county='$newcounty',
city='$newcity',
province='$newprovince',
zip_code='$newzipCode',
state='$newstate'
WHERE customer_id='$currentID'
";
$conn->query($query) or die($conn->error.__LINE__);
// Bring user back to index
header("Location: index.php?alert=savechanges");
// Close connection to database
$conn->close();
}
the above query runs fine, but the row is not updated. all the field names are appropriate. When the query is tried in phpMyAdmin, row updated.
Please help, thank you.
Your validateInputData() function is not doing any validation. Hopefully it's doing some escaping, implying that you are assuming global scope for your database connection object. You didn't tell us what type of database object this is. Your error checking is poor. You don't do an explicit exit after the redirect.
Apart from that the sql looks ok.

How to implement "WHERE NOT IN" query into Codeigniter Active records?

I have a MySQL query which is this:
SELECT * FROM tbl_post WHERE tbl_post.post_id NOT IN
(SELECT tbl_readsave.post_id FROM tbl_readsave)
I want to convert it into Codeigniter Active records, so I used the following code segment:
$this->db->select('tbl_readsave.post_id');
$queryReadSave = $this->db->get('readsave');
$this->db->where_not_in('post_id', $queryReadSave->result_array());
$queryNewPost = $this->db->get('readsave');
if($queryNewPost->num_rows()>0)
{
return $queryNewPost->result_array();
}
else
return false;
However, the code throws me an error, which is like the following:-
Error Number: 1054
Unknown column 'Array' in 'where clause'
SELECT * FROM (`tbl_readsave`) WHERE `post_id` NOT IN (Array)
Filename: /var/www/html/teamF/tharjumal/models/webservice_model.php
Line Number: 28
How can I convert the above stated query into Codeigniter Active Records format?
$queryReadSave->result_array() returns an array of arrays. You can't use that in where_not_in.
You need to loop over that and create a flat array of the IDs you (don't) want.
$this->db->select('post_id');
$queryReadSave = $this->db->get('readsave');
$postIDs = $queryReadSave->result_array();
$this->db->where_not_in('post_id', array_column($postIDs, 'post_id'));
$queryNewPost = $this->db->get('post');
array_column() only exists in PHP 5.5+. If you are on a lower version, you'll need to do something like this:
$this->db->select('post_id');
$queryReadSave = $this->db->get('readsave');
$postIDs = array_map(function($a){
return $a['post_id'];
}, $queryReadSave->result_array());
$this->db->where_not_in('post_id', $postIDs);
$queryNewPost = $this->db->get('post');
P.S. Your second table is called post, right? You'll need to update the query to use the right table.
Update: Your original query uses a subquery which is not natively supported by CodeIgniter. If you want to try this all as one query, you can use the Subquery library I created (https://github.com/NTICompass/CodeIgniter-Subqueries).
$this->db->select('*');
$this->db->from('post');
$sub = $this->subquery->start_subquery('where_in');
$sub->select('post_id')->from('readsave');
$this->subquery->end_subquery('post_id', FALSE);
$queryNewPost = $this->db->get();
try below code:
$read_post_id = [];
$queryReadSave = $this->db->select('post_id')->get('tbl_readsave')->result_array();
if(count($queryReadSave) > 0){
foreach($queryReadSave as $row){
$read_post_id[] = $row['post_id']; // add each post id to the array
}
}
$this->db->select('*');
if(!empty($read_post_id)) $this->db->where_not_in('post_id',$read_post_id);
$post = $this->db->get('tbl_post');
print_r($post->result_array());
exit;

Adding array value in php query on Joomla

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,

Codeigniter - SQL error. Driving me crazy

Here is my code:
$child = $this->getDetails($row['ParentOf_Id']);
which is in another function that calls a function called getdetails:
function getDetails($child_id=null,$limit=20){
// select all the fields in the children table
$this->db->select(castedColumns($this->children_table, $this->db));
//where the id is the child id
$q = $this->db->get_where($this->children_table, 'id='.$child_id);
//store results array in details
$details = $q->row_array();
I then get the following SQL error:
A Database Error Occurred
Error Number:
Incorrect syntax near '='.
SELECT CAST(AdditionalNotes AS TEXT) as AdditionalNotes, CAST(DisabilitiesNotes AS TEXT) as DisabilitiesNotes, DOB, msrepl_tran_version FROM Children WHERE id=
Id does not get appended? why?
Been driving me nuts because, when I do echo $child_id; I get the child Id before passing it into the SQL.
try:
$this->db->select(castedColumns($this->children_table, $this->db));
$q = $this->db->get_where($this->children_table, array('id' => $child_id));
$details = $q->row_array();
I would guess that $child_id is null, otherwise it would show in the db error query. Try to print $child_id and see if it's really a null which would mean that
$child = $this->getDetails($row['ParentOf_Id']);
$row['ParentOf_Id'] is null.

PHP & MS SQL: sp_helpconstraint <tablename> will not allow me to advance to the second data set with mssql_next_result()...?

I am trying to get the full definition for constraints on a particular table in MSSQL via PHP's mssql.dll driver, and when I call next_result() on the returned resource from the original query "sp_helpconstraint ", I either get an empty result set, or it does not advance to the next table of data...
IS there a direct query to the sys. tables that I can make that will pull the equivalent information without the extra data set?
This same problem seems to exist with the SQL SERVER ddl supplied by MS as well.
Code is as follows:
$sql = '/* Getting '.$this->ExpectedTableVO->GetTableName().' Constraints */ sp_helpconstraint \''.$this->ExpectedTableVO->GetSchema().'.'.$this->ExpectedTableVO->GetTableName().'\'';
$r = $this->db->Query($sql);
$results['Constraints'] = array();
$r = $this->db->NextResult($r);
while ($row = $this->db->FetchObj($r))
{
$results['Constraints'][] = $row;
}
This results in an empty set, despite there being plenty of constraints on the table in question. Without NextResult, I get the Table with a single row and column "Object Name" with the table name...
Otherwise an empty set... WTF?!
I messed up...
Notice I overwrite $r with the nextresult() command... just calling that without overwriting it fixes this problem.
$sql = '/* Getting '.$this->ExpectedTableVO->GetTableName().' Constraints */ sp_helpconstraint \''.$this->ExpectedTableVO->GetSchema().'.'.$this->ExpectedTableVO->GetTableName().'\'';
$r = $this->db->Query($sql);
$results['Constraints'] = array();
$r = $this->db->NextResult($r);
//above line should be just "$this->db->NextResult($r);"
while ($row = $this->db->FetchObj($r))
{
$results['Constraints'][] = $row;
}

Categories