My SQL query is based on data provided.
For example :
// table
$table = new Model_MyTable_DbTable();
// data
$columns = array( 'column1', 'column2', 'column3' );
// query
$select = $table->select();
$select->where('deleted = ?', '0' );
for( $i = 0; $i < count( $columns ); $i++ ) {
if( $i == 0 ) {
$select->where( $columns[$i] . ' > ?', '0' );
} else {
$select->orWhere( $columns[$i] . ' > ?', '0' );
}
}
$select->where('disabled = ?', '0' );
// print query
echo $select->assemble();die();
Above code result into following query:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0') OR (column2 > '0') OR (column3 > '0') AND
(disabled = '0')
But I want something like this:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0' OR column2 > '0' OR column3 > '0') AND
(disabled = '0')
How it is possible ?
Thanks
I think this should do the job:
// table
$table = new Model_MyTable_DbTable();
// data
$columns = array('column1', 'column2', 'column3');
// query
$select = $table->select();
$select->where('deleted = ?', '0');
$myOrParts = array();
for ($i = 0; $i < count($columns); $i++) {
$myOrParts []= $table->getAdapter()->quoteInto($columns[$i] . ' > ?', '0');
}
$myWhere = implode(' OR ', $myOrParts);
$select->where(new Zend_Db_Expr($myWhere));
$select->where('disabled = ?', '0');
// print query
echo $select->assemble();
die();
Related
With this code, I parse post elements from table
$all = R::findAll('postdate'," ORDER BY id DESC LIMIT 15");
for($i = 1; $i <= count($all); $i++){
if(isset($all[$i])){
$date = date_create($all[$i]->date);
$post = R::findOne('post', 'date_id = ?', array($all[$i]->id));
$author = R::findOne('postauthor', 'id = ?', array($post->author_id));
$title = R::findOne('posttitle', 'id = ?', array($post->title_id));
echo '<div class=post>
<i class=post-date>'.date_format($date, 'd.m.Y G:i').' 📝 '.$author->author.'</i>
<h1>'.$title->title.'</h1><hr><br>'.
$post->content.
'</div>';
}
}
but in the end the last posts are not found and everything goes in ascending order. Help me please. I tried it through the date too
$all = R::getAll( 'SELECT * FROM postdate ORDER BY date DESC LIMIT 125' );
for($i = -1; $i <= count($all); $i++){
if(isset($all[$i])){
$date = date_create($all[$i]['date']);
$post = R::findOne('post', 'date_id = ?', array($all[$i]['id']));
$author = R::findOne('postauthor', 'id = ?', array($post->author_id));
$title = R::findOne('posttitle', 'id = ?', array($post->title_id));
echo '<div class=post>
<i class=post-date>'.date_format($date, 'd.m.Y G:i').' 📝 '.$author->author.'</i>
<h1>'.$title->title.'</h1><hr><br>'.
$post->content.
'</div>';
}
}
I have about 4000 dates in my database table. From this data I would need the total count that has the same month and year in an array with year and the month and total result. The array must look like this: $ year ['year'] [strftime ('% Y', $ application ['crdate'])] ['month'] [$ i] = intval ($ application ['erg']);
Rendered like that example:
[year, month jan (01), month feb (02), ...]
With data:
[2016, 0, 0, 0, 4, 0, 9, 0, 0, 0, 0, 0, 2]
I have the following code to do this, but it needs to load forever with 4000 records. Why is it so slow and how can I speed it up?
$year = array();
$where_month = false;
if($this->request->hasArgument('time')) {
$von = $this->request->getArgument('time')['von'];
$bis = $this->request->getArgument('time')['bis'];
$von_jahr = strftime('%Y',strtotime($von));
$bis_jahr = strftime('%Y',strtotime($bis));
$von_englisch_format = strftime('%Y-%m-%d',strtotime($von));
$bis_englisch_format = strftime('%Y-%m-%d',strtotime($bis));
$von_stamp = strtotime($von);
$bis_stamp = strtotime($bis);
$where_month = true;
}
for($i = 1; $i <= 12; $i++) {
if ($i <= 9) {
$i = '0' . $i;
}
$select_fields = 'T1.*';
$from_table = ' datas T1';
if($where_month) {
$where_clause = 'DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") >= "'.$von_jahr.'" AND DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") <= "'.$bis_jahr.'"';
} else {
$where_clause = '';
}
$groupBy = '';
$orderBy = 'crdate ASC';
$limit = '';
$erg = 0;
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
foreach($result as $bewerbung) {
$year['jahr'][strftime('%Y', $bewerbung['crdate'])]['monat'][$i] = 0;
$select_fields = '*, count(*) AS erg';
$from_table = ' datas T1';
if($where_month == false) {
$where_clause = 'DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") = "' . strftime('%Y', $bewerbung['crdate']) . '" AND DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "' . $i . '"';
} else {
$where_clause = '(DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y-%m-%d") BETWEEN "'.$von_englisch_format.'" AND "'.$bis_englisch_format.'") AND DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") = "' . strftime('%Y', $bewerbung['crdate']) . '" AND DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "' . $i . '"';
}
$groupBy = '';
$orderBy = 'crdate ASC';
$limit = '';
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
foreach ($result as $bewerbung) {
if (intval($bewerbung['erg']) >= 1) {
$year['jahr'][strftime('%Y', $bewerbung['crdate'])]['monat'][$i] = intval($bewerbung['erg']);
}
}
}
}
my new solution looks like this:
$select_fields = 'T1.*, DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y") AS "jahr",
COUNT( CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "01"
THEN 1
ELSE NULL
END
) AS "januar",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "02"
THEN 1
ELSE NULL
END
) AS "februar",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "03"
THEN 1
ELSE NULL
END
) AS "maerz",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "04"
THEN 1
ELSE NULL
END
) AS "april",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "05"
THEN 1
ELSE NULL
END
) AS "mai",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "06"
THEN 1
ELSE NULL
END
) AS "juni",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "07"
THEN 1
ELSE NULL
END
) AS "juli",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "08"
THEN 1
ELSE NULL
END
) AS "august",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "09"
THEN 1
ELSE NULL
END
) AS "september",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "10"
THEN 1
ELSE NULL
END
) AS "oktober",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "11"
THEN 1
ELSE NULL
END
) AS "november",
COUNT(
CASE
WHEN DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%m") = "12"
THEN 1
ELSE NULL
END
) AS "dezember"';
$from_table = ' tx_lemmbewerberportal_domain_model_bewerbungen T1';
$where_clause = '';
$groupBy = 'DATE_FORMAT(FROM_UNIXTIME(T1.crdate), "%Y")';
$orderBy = 'crdate ASC';
$limit = '';
$erg = 0;
$result = $GLOBALS['TYPO3_DB']->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
$i = 0;
foreach ($result as $row) {
$year[$i]['jahr'] = $row['jahr'];
$year[$i]['01'] = $row['januar'];
$year[$i]['02'] = $row['februar'];
$year[$i]['03'] = $row['maerz'];
$year[$i]['04'] = $row['april'];
$year[$i]['05'] = $row['mai'];
$year[$i]['06'] = $row['juni'];
$year[$i]['07'] = $row['juli'];
$year[$i]['08'] = $row['august'];
$year[$i]['09'] = $row['september'];
$year[$i]['10'] = $row['oktober'];
$year[$i]['11'] = $row['november'];
$year[$i]['12'] = $row['dezember'];
$i++;
}
return $year;
Within a second, the data is loaded. Thank you anyway. :-)
I try to use GroceryCRUD with SQL Server (2008 R2) to manage some table.
Well, I find the following thread very usefull on StackOverflow :
How can I run grocery with sql server?
But, when I use $this->grocery_crud->set_relation, it returns an error "PrimaryKey not found" on the method set_primary_key.
The table obviously has correctly set the primary key.
Can someone help me figure out where is the problem?
Ok. This is how I hack the code:
ref.version:
grocery-crud-1.5.2
CodeIgniter-3.0.1
STEP 1
File: system\database\drivers\pdo\subdrivers\pdo_sqlsrv_driver.php
Update method field_data($table)
public function field_data($table)
{
$sql = 'SELECT c.COLUMN_NAME, c.DATA_TYPE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.COLUMN_DEFAULT
,CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS KeyType
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN (
SELECT ku.TABLE_CATALOG,ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS ku
ON tc.CONSTRAINT_TYPE = \'PRIMARY KEY\'
AND tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME
) pk
ON c.TABLE_CATALOG = pk.TABLE_CATALOG
AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.COLUMN_NAME = pk.COLUMN_NAME
WHERE UPPER(c.TABLE_NAME) = '.$this->escape(strtoupper($table));
if (($query = $this->query($sql)) === FALSE)
{
return FALSE;
}
$query = $query->result_object();
$retval = array();
for ($i = 0, $c = count($query); $i < $c; $i++)
{
$retval[$i] = new stdClass();
$retval[$i]->name = $query[$i]->COLUMN_NAME;
$retval[$i]->type = $query[$i]->DATA_TYPE;
$retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION;
$retval[$i]->primary_key = $query[$i]->KeyType;
$retval[$i]->default = $query[$i]->COLUMN_DEFAULT;
}
return $retval;
}
STEP 2
File: \system\database\drivers\sqlsrv\sqlsrv_driver.php
Update method field_data($table)
public function field_data($table)
{
$sql = 'SELECT c.COLUMN_NAME, c.DATA_TYPE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.COLUMN_DEFAULT
,CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS KeyType
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN (
SELECT ku.TABLE_CATALOG,ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS ku
ON tc.CONSTRAINT_TYPE = \'PRIMARY KEY\'
AND tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME
) pk
ON c.TABLE_CATALOG = pk.TABLE_CATALOG
AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.COLUMN_NAME = pk.COLUMN_NAME
WHERE UPPER(c.TABLE_NAME) = '.$this->escape(strtoupper($table));
if (($query = $this->query($sql)) === FALSE)
{
return FALSE;
}
$query = $query->result_object();
$retval = array();
for ($i = 0, $c = count($query); $i < $c; $i++)
{
$retval[$i] = new stdClass();
$retval[$i]->name = $query[$i]->COLUMN_NAME;
$retval[$i]->type = $query[$i]->DATA_TYPE;
$retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION;
$retval[$i]->primary_key = $query[$i]->KeyType;
$retval[$i]->default = $query[$i]->COLUMN_DEFAULT;
}
return $retval;
}
STEP 3
File: \system\database\drivers\mssql\mssql_result.php
Update method field_data()
public function field_data()
{
$retval = array();
for ($i = 0, $c = $this->num_fields(); $i < $c; $i++)
{
$field = mssql_fetch_field($this->result_id, $i);
$retval[$i] = new stdClass();
$retval[$i]->name = $field->name;
$retval[$i]->type = $field->type;
$retval[$i]->max_length = $field->max_length;
$retval[$i]->primary_key = $field->primary_key;
}
return $retval;
}
That's all. I hope it can help other people.
i misunderstand why my query gives me entrys with an Timestamp of 0. Can anyone say me what im doing wrong?
Query:
SELECT
*
FROM
`changes`
WHERE
`time_from`>=1393628400
AND
`time_to`<=1394838000
AND
`area`='USERNAME'
ORDER BY
`time_from` DESC,
`time_to` DESC
PHP
$time_from = (isset($_POST['time_from']) ? strtotime($_POST['time_from']) : null);
$time_to = (isset($_POST['time_to']) ? strtotime($_POST['time_to']) : null);
if(empty($time_from) && empty($time_to)) {
/* Do Nothing */
} else {
if(!empty($time_from) && $time_from > 0 && !empty($time_to) && $time_to > 0) {
$query = sprintf(' `time_from`>=%d AND `time_to`<=%d', $time_from, $time_to);
} else if(!empty($time_from) && $time_from > 0) {
$query = sprintf(' `time_from`>=%d', $time_from);
} else if(!empty($time_to) && $time_to > 0) {
$query = sprintf(' `time_to`<=%d', $time_to);
}
$results = $wpdb->get_row(sprintf('SELECT COUNT(*) AS `count` FROM `%sarea_changes` WHERE%s AND `area`=\'%s\'', $wpdb->prefix, $query, $user->user_login));
$count = $results->count;
if($count < 10) {
$position = 0;
$has_more_pages = false;
}
$pages = ceil($count / $max_rows);
$query = sprintf('SELECT * FROM `%sarea_changes` WHERE%s AND `area`=\'%s\' ORDER BY `time_from` DESC, `time_to` DESC', $wpdb->prefix, $query, $user->user_login, $position, $max_rows);
print $query;
$entrys = $wpdb->get_results($query); // LIMIT %d, %d
}
POST Data:
time_from is 01.03.2014 and time_to is 15.03.2014
But i get following entrys (see the time_to), why is that 0 that dont match my Query?
Screenshot:
(Hidden data for privacy policy)
I have a website with a small searching script, where I use utf-8 charset.
Now on my mysql database I use the latin1_swedish_ci charset.
When I want to search for something that has the letters å,ä or ö it doesn't return any results because in the database the letter å=Ã¥, ä=ä and ö=ö.
The solution to this problem would be telling the search script to replace these letters with those that the database understands.
So when my users search for something that has the letter å in it, it should convert it to Ã¥ and return proper results.
Any idea how to achieve this?
Thanks in advance
EDIT:
Added the script that im trying to modify, but with no luck.
Any idea on how to modify it so that it "converts" the charset:
<?php
// file for database connection
include('inc/db.inc.php');
// configuration file
include('inc/config.inc.php');
if(isset($_GET['p'])) {
$page_number = $_GET['p'];
$arraySearch = $_GET['terms'];
$show_count = $_GET['count'];
settype($page_number, 'integer');
}
$nospaces = substr($_GET['terms'],0,4);
$offset = ($page_number - 1) * $records_number;
// check for an empty string and display a message.
if ($_GET['terms'] == "") {
echo '<div id="counter">ex. write ´here and´ or ´search´ without quotes.</div>';
// minim 3 characters condition
} else if(strlen($_GET['terms']) < $limitchar) {
echo '<div id="counter">'. $limitchar .' characters minimum</div>';
// no spaces in first 4 letters
} else if(preg_replace('/[a-zA-Z0-9]/', '', $nospaces)) {
echo '<div id="counter">Please use letters or numbers in first 4 characters</div>';
} else {
// explode search words into an array
$arraySearch = explode(" ", $_GET['terms']);
// table fields to search
$arrayFields = array(0 => $first_field, 1 => $second_field);
$countSearch = count($arraySearch);
$a = 0;
$b = 0;
$query = "SELECT * FROM $table_name WHERE (";
$countFields = count($arrayFields);
while ($a < $countFields)
{
while ($b < $countSearch)
{
$query = $query."$arrayFields[$a] LIKE '%$arraySearch[$b]%'";
$b++;
if ($b < $countSearch)
{
$query = $query." AND ";
}
}
$b = 0;
$a++;
if ($a < $countFields)
{
$query = $query.") OR (";
}
}
$query = $query.") LIMIT $offset, $records_number;";
$search = mysql_query($query);
// get number of search results
$arrayFields = array(0 => $first_field, 1 => $second_field);
$countSearch = count($arraySearch);
$a = 0;
$b = 0;
$query = "SELECT * FROM $table_name WHERE (";
$countFields = count($arrayFields);
while ($a < $countFields)
{
while ($b < $countSearch)
{
$query = $query."$arrayFields[$a] LIKE '%$arraySearch[$b]%'";
$b++;
if ($b < $countSearch)
{
$query = $query." AND ";
}
}
$b = 0;
$a++;
if ($a < $countFields)
{
$query = $query.") OR (";
}
}
$query = $query.")";
$count_results = mysql_query($query);
$numrows = mysql_num_rows($count_results);
// no results
if($numrows == 0) {
echo '<div id="counter">No results found</div>';
// show results
} else {
echo '<div id="results">
<div id="results_top"><p><b>'. $_GET['terms'] .'</b> - '. $numrows .' results found</p></div>
';
while($row = mysql_fetch_assoc($search)) {
$urltitle = str_replace(" ","_", $row['title']);
echo '<div class="item">
<div class="details"><img src="http://www.onlinegamez.net/files/image/'.$row['icon'].'" width="90" height="65" alt="'.$row['title'].'"/>'.$row['title'].'<br />
'.$row['description'].'</div>
<div class="played"><span>'.$row['timesplayed'].'</span>
<p>played</p></div>
<div style="clear:both;"></div></div>';
}
// pagination
$maxPage = ceil($numrows/$records_number);
$nav = '';
for($page = 1; $page <= $maxPage; $page++) {
if ($page == $page_number) {
$nav .= "$page";
}
else
{
$nav .= "$page";
}
}
if ($page_number > 1) {
$page = $page_number - 1;
$prev = "«";
$first = "First";
}
else {
$prev = '';
$first = '';
}
if ($page_number < $maxPage) {
$page = $page_number + 1;
$next = "»";
$last = "Last";
}
else {
$next = '';
$last = '';
}
echo $data;
echo "<div id=\"results_bottom\"><p>$first $prev $nav $next $last</p></div>
</div>";
}
}
?>
First of all -- why are you using different charsets?
There are several ways to attack you problem, you could change the charset on connection;
set names 'utf8';
set character set 'utf8' collate 'utf8_swedish_ci';
You could do a collation based match;
select
`field`
from
`table`
where
cast(`field` as char character set 'utf8') collate 'utf8_swedish_ci' = '$PHP_VARIABLE'
Or you could change the charset on the variable in PHP;
$var_in_iso88591 = utf8_decode($var_in_utf8);
Look into utf8_encode()/utf8_decode() and iconv()