it-swarm.com.de

Hilfe beim Verketten einer Abfrage?

ich habe Mühe, die richtige Syntax für meine Abfrage zu erhalten. Die Abfrage lautet:

$query = "SELECT product_sku FROM #__virtuemart_products WHERE created_on <= NOW();";

Ich habe derzeit:

$query
    ->select($db->quoteName(array('product_sku')))
    ->from($db->quoteName('#__virtuemart_products'))
    ->where($db->quoteName('created_on') . ' >=NOW();)
    ->order('ordering ASC');

Aber es gibt mir einen 500 Server Fehler.

Irgendwelche Ideen?

Beste Grüße Donna

Bearbeiten: Dies ist so, ich benutze die Joomla API in meinem PHP korrekt. Edit 2: Vollständiger Code ist unten:

<?php

//display errors
error_reporting(E_ALL);
ini_set("display_errors", 1);

//init Joomla Framework 
define('_JEXEC', 1); 
define('JPATH_BASE', dirname(__FILE__).'/');
define('JPATH_COMPONENT',dirname(__FILE__).'/');
define('DS', DIRECTORY_SEPARATOR); 

//echo JPATH_BASE;

require_once (JPATH_BASE .DS. 'includes' .DS. 'defines.php'); 
require_once (JPATH_BASE .DS. 'includes' .DS. 'framework.php');

// Start database stuff
$db = JFactory::getDbo();

//Select records that were created today
$query = "SELECT product_sku FROM #__virtuemart_products WHERE created_on >= NOW();";


//The query below needs fixing
/*$query->select($db->quoteName(array('product_sku')))
    ->from($db->quoteName('#__virtuemart_products'))
    ->where('created_on >= NOW()')
    ->order('ordering ASC');*/

$db->setQuery($query);

$result = $db->loadObjectList();
$result = $db->execute();
$my_count = $db->getNumRows($result); 
//echo($my_count);

//Check if any records are returned, if none then end
if ($my_count == 0){
echo "No records found";
exit;
}

if (!$result) die('Couldn\'t fetch records');
$headers = $result -> fetch_fields();
foreach($headers as $header) {
$head[] = $header->name;
}


// Check if the file already exists, if so delete it

$filename = '/home/website/public_html/temp_cron/new.csv';

if (file_exists($filename)) {
    array_map('unlink', glob($filename));
    //echo "The file $filename has been deleted";
}

$fp = fopen($filename, 'x');
if ($fp && $result) {
fputcsv($fp, array_values($head)); 
while ($row = $result->fetch_array(MYSQLI_NUM)) {
    fputcsv($fp, array_values($row));
}

}    


/********************************************
/
/Send new product sku's to admin
/
/********************************************/

$mailer = JFactory::getMailer();

$config = JFactory::getConfig();
$sender = array( 
    $config->get( 'mailfrom' ),
    $config->get( 'fromname' ) 
);

$mailer->setSender($sender);
//echo "it works";
$user = JFactory::getUser();
$recipient = '[email protected]';

$mailer->addRecipient($recipient);

$body   = "New products have been added to the catalog.";
$mailer->setSubject('New Products Added');
$mailer->setBody($body);
// Optional file attached
$mailer->addAttachment($filename);

$send = $mailer->Send();

if ( $send !== true ) {
    echo 'Error sending email: ' . $send->__toString();
} else {
    echo 'Mail sent';
    }
die;
?>
2
Dtorr1981

Versuchen Sie diesen Code -

// Start database stuff
$db = JFactory::getDbo();

// Create a new query object.
$query = $db->getQuery(true); //-> you are missing this

//Select records that were created today
$query->select($db->quoteName(array('product_sku')))
    ->from($db->quoteName('#__virtuemart_products'))
    ->where($db->quoteName('created_on') . ' >= NOW()')
    ->order('ordering ASC');

$db->setQuery($query);

$result = $db->loadObjectList();
$result = $db->execute();
$my_count = $db->getNumRows($result); 

Bitte auch entfernen

$result = $db->execute();

Es ist hier nicht erforderlich.

Einige nützliche Links

  1. Daten mit JDatabase auswählen
  2. Einfügen, Aktualisieren und Entfernen von Daten mit JDatabase

Ich hoffe es wird für dich funktionieren :)

4
Joomler

Das Folgende ist die richtige Reihenfolge:

$db->setQuery($query);
$db->execute();
$my_count = $db->getNumRows(); 
$result = $db->loadObjectList();

Es ist interessant, da dieser Code ausreicht, um nur die Ergebnisse zu erhalten:

$db->setQuery($query);
$result = $db->loadObjectList();

Es ist lächerlich, einen 500-Fehler zu bekommen. Ich meine, ich habe eine Nginx-Fehlerseite, daher wurde die Ausnahme nicht von Joomla abgefangen ...

1
inf3rno

Kritisch ist, dass Sie den Vergleich der WHERE -Klausel anpassen müssen, damit Sie ALLE Produkte des Tages sammeln. Ich habe mein Snippet mit Inline-Kommentaren, Verfeinerungen, Checkpoints, Debugging-Funktionen und einer einzelnen/verketteten Antwortzeichenfolge gepackt, um mir selbst eine E-Mail zu senden.

$body = "";
$db = JFactory::getDBO();
try {
    $query = $db->getQuery(true)
                ->select("product_sku")                   // string, not an array
                ->from("#__virtuemart_products")
                ->where("DATE(created_on) = CURDATE()")   // Y-m-d portion = Today's date
                ->order('ordering');                      // ASC is the default
    $db->setQuery($query);
    if (!$result = $db->loadAssocList()) {                // check and store for later
        $body = "<div>No Product Today (date: " . date("Y-m-d") . ")</div>";
        // I don't know if you want to delete the old .csv on this fork
    } else {
        $head = array_keys($result[0]);  // I'm not sure why this is dynamic (it's hardcoded as "product_sku")

        // Overwrite CSV
        $filename = '/home/website/public_html/temp_cron/new.csv';

        // Without *, no need to glob():  http://php.net/manual/en/function.unlink.php#109971
        if (file_exists($filename)) {
            if (unlink($filename)) {
                $body .= "<div>Deleted old .csv</div>";
            } else {
                $body .= "<div>Failed to deleted old .csv</div>";
            }
            $body .= "<div>Old .csv not found</div>";
        }

        $written = true;
        if (!$fp = fopen($filename, 'x')) {  // run and check
            $body .= "<div>Failed to generate handle for new .csv</div>";
            $written = false;
        } else {
            if (!fputcsv($fp, $head)) {  // run and check for failure or zero-length string
                $body .= "<div>Failed to write head row for new .csv (file write halted)</div>";
                $written = false;
            } else {
                foreach ($result as $row) {
                    if (fputcsv($fp, $row) === false) {  // run and check for success (allowing empty string)
                        $body .= "<div>Failed to write data row for new .csv (row: " . implode(" , ", $row) . ") (file write halted)</div>";
                        $written = false;
                        break;  // end the loop
                    }
                }
            }
            fclose($fp);
        }
        if ($written) {
            $body .= "<div>Successfully wrote " . sizeof($result) . " row(s) to the .csv</div>";
        }
    }
} catch (Exception $e) {
    $body = "Failure Occurred:<br>" . $query->dump() . "<br>" . $e->getMessage();
}
// ... proceed with emailing portion to deliver $body message to developer
0
mickmackusa