ModX PDO SQL returns empty array - pdo

I pretty much copy/pasted this from the ModX RTFM:
$results = $modx->query("SELECT * FROM `saved_jobs` WHERE `job_id` = $job_id AND `user_id` = $user");
if (!is_object($results)) {
return 'No result!';
}
else {
$r = $results->fetchAll(PDO::FETCH_ASSOC);
echo $r;
echo "<br>count " . count($r);
print_r($r);
}
But even though there are no records in the database I still get the 'else' occurring. The line echo "count " . count($r); produces the output: count 0
Does anyone know whats going on and how to fix it?

If your query is successful, you still create an object with your first statement.
take a peek [also from the docs]:
$result = $modx->query("SELECT * FROM modx_users WHERE id='blah'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return 'No result!';
}
else {
$row = $result->fetch(PDO::FETCH_ASSOC);
return 'Result:' .print_r($row,true);
}
What you want to do is find out if the object actually contains a result set:
$result = $modx->query("SELECT * FROM modx_users WHERE id='1'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return FALSE;
}
if(sizeof($result) > 0){
while($row = $result->fetch(PDO::FETCH_ASSOC)){
echo'Result:' .print_r($row,true);
}
}
so you can either test the size of the $result variable or just run the while loop & test if it has any data as well.

Related

I can't access admin panel of my script : Invalid query You have an error in your SQL syntax

I have an error message when i try to access my script (php):
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 's marketing advertising'' at line 1
This is a admin php file contain mysql query
<?php
$stt_query = $ocdb->get_rows("SELECT * FROM ".$config->prefix."search order by id desc limit 13" );
if (count( $stt_query ) > 0) {
foreach ($stt_query as $row) :
?>
<li><?php echo $row['title'];?></li>
<?php
endforeach;
}
?>
the php query page:
<?php class OCDB { var $server = ""; var $port = ""; var $db = ""; var $user = ""; var $password = ""; var $prefix = ""; var $insert_id; var $link; function __construct($_server, $_port, $_db, $_user, $_password, $_prefix) { $this->server = $_server; $this->port = $_port; $this->db = $_db; $this->user = $_user; $this->password = $_password; $this->prefix = $_prefix; $host = $this->server; if (defined('DB_HOST_PORT') && !empty($this->port)) $host .= ':'.$this->port; $this->link = mysqli_connect($host, $this->user, $this->password) or die("Could not connect: " . mysqli_connect_error()); mysqli_select_db($this->link, $this->db) or die ('Can not use database : ' . mysqli_error($this->link)); mysqli_query($this->link, 'SET NAMES utf8'); } function get_row($_sql) { //$res = $this->link->query($_sql); //if ($this->link->error) { //try { //throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $this->link->errno); //} catch(Exception $e ) { //echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >"; //echo nl2br($e->getTraceAsString()); //} //} $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_ASSOC); mysqli_free_result($result); return $row; mysqli_close($this->link); } function get_rows($_sql) { $rows = array(); $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $rows[] = $row; } mysqli_free_result($result); return $rows; } function get_var($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_NUM); mysqli_free_result($result); if ($row && is_array($row)) return $row[0]; return false; } function query($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $this->insert_id = mysqli_insert_id($this->link); return $result; } function escape_string($_string) { return mysqli_real_escape_string($this->link, $_string); } } ?>
Please can you help me i can't access admin panel because of this error.
Thanks

Check if AD group exists or not

Trying to check if AD group exists or not using below script :
$Path = "LDAP://dc=cmc,dc=com"
$object = "CMC\QTKS-DEP-Admin-Temp"
$type = "Group"
$search = [System.DirectoryServices.DirectorySearcher]$Path
$search.Filter = "(&(name=$object)(objectCategory=$type))"
$Result = $search.FindOne()
IF( $Result -eq $null)
{
Write-Host "Group does not exist"
}
Else
{
Write-Host "Group exists"
}
I know something wrong with the LDAP connection string or variables declarations. Or something else. Can someone please correct. The result always shows as "Group does not exist" even if it exists.
Got it finally :
$Search = New-Object DirectoryServices.DirectorySearcher
$Search.Filter = '(&(objectCategory=Group)(anr=CMC\QTKS-DEP-Admin-Temp))'
$Search.SearchRoot = 'LDAP://DC=cmc,DC=com'
$Result = $Searcher.FindOne()
IF( $Result -eq $null)
{
Write-Host "Group does not exist"
}
Else
{
Write-Host "Group exists"
}

yii phpexcel file reader no response

I have a piece of code that is
$excelFile = '/tmp/sheet.xls' ;
Yii::import('application.vendors.PHPExcel',true);
$inputFileType = PHPExcel_IOFactory::identify($excelFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($excelFile);
$objWorkSheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorkSheet->getHighestRow();
$hightestColumn = $objWorkSheet->getHightestColumn();
$hightestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<table>'."\n" ;
for($row=2; $row<$highestRow ; ++$row){
echo '<tr>'."\n" ;
for($col=0; $col < $highestColumnIndex ; ++$col){
echo '<td>'.$objWorksheet->getCellByColumnAndRow($col,$row)->getValue().'</td>'."\n";
}
echo '</tr>'."\n" ;
}
echo '</table>'."\n" ;
But when this code execute I do not get any file display. I also tried to put debugs to check where it failed, I could localize the error to getActiveSheet.
Any help would be appreciated
Thanks
Try import PHPExcel like this:
spl_autoload_unregister(array('YiiBase', 'autoload'));
Yii::import('application.vendors.PHPExcel', true);
$this->objPHPExcel = new PHPExcel();
spl_autoload_register(array('YiiBase', 'autoload'));
Here is how i display the imported excel file and works:
spl_autoload_unregister(array('YiiBase','autoload'));
Yii::import("application.vendors.phpexcel.Classes.PHPExcel", true);
$inputFileType = PHPExcel_IOFactory::identify($path);
$objReader = PHPExcel_IOFactory::createReader($inputFileType); //Excel5);
$objPHPExcel = $objReader->load($path);
spl_autoload_register(array('YiiBase','autoload'));
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$rowIndex=$row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cellIndex=>$cell) {
if (!is_null($cell)) {
if($rowIndex >1 && $cellIndex<=55){
$cellVal=$cell->getCalculatedValue();
echo $cellVal;
}
}
}
}
}

Varchar takes zero field empty

I have a table with a series of codes, which has a field called "numerousuarios" which has a default value "0"
Here the code:
$statement = " SELECT numerousuarios FROM codigos WHERE codigos = :codigo";
$sth = $db ->prepare($statement);
$sth -> execute(array(':codigo'=>$codigo));
$result = $sth->fetch();
$mivariable = $result[numerousuarios];
if(!empty($mivariable)){
if($mivariable>=5){
echo "the code is full users";
}
else{
// Do something...
}
}
else{
echo "el codigo no existe";
}
The if (empty ($ myvar)) is to see if that record in the database.
The problem is that if the value is "0" I take it as an empty field.
What am I doing wrong?
You say the result is "0" by default .just check the returend value is not equal 0 :)
$statement = " SELECT numerousuarios FROM codigos WHERE codigos = :codigo";
$sth = $db ->prepare($statement);
$sth -> execute(array(':codigo'=>$codigo));
$result = $sth->fetch();
$mivariable = $result[numerousuarios];
if($mivariable !=0){
if($mivariable>=5){
echo "the code is full users";
}
else{
// Do something...
}
}
else{
echo "el codigo no existe";
}
:)

How can I unserialize data from database after it was serialized

try {
if (isset($_SESSION['list']) > 0) {
$test = serialize($_SESSION["list"]);
$sQuery = "INSERT INTO table (id, date) VALUES ('$test', NOW())";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
}
else {
echo 'No data';
}
}
In my database I see this:
1 a:1:{i:1;s:1:"5";} 2011-12-21
The $_SESSION['list'] stores ID and the QUANTITY.
The data a:1:{i:1;s:1:"5";} is as follow: i=id, s=id:"quantity", I read this as id=1 and the quantity of id=1 is 5, am I correct?
Now I want select the data and unserialize the array.
try {
$sQuery = "SELECT * FROM table";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetchALL(PDO::FETCH_ASSOC)) {
$id = unserialize($aRow['id']);
foreach($id as $id => $quantity) {
echo $id.', ';
}
}
}
catch(PDOException $e) {
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
What am I doing wrong or what can I do so I can select the ID and QUANTITY from database?
The serialization/deserialization part looks fine to me, but the $oStmt->fetchALL( I think should be $oStmt->fetch(, and in foreach($id as $id => $quantity) { use another variable to hold the key instead of id, like foreach($id as $key => $quantity) {.
Also, you don't echo the quantity anywhere. Change echo $id.', '; to echo $key.' '.$quantity; or something and tell us what the output is so we can help further.