Adapt MySQL query to JDatabase query - mysql

I am trying to execute a query through Joomla 2.5.
By using the following MySQL query, it performs correctly:
$query = "REPLACE INTO fa_usr (id, date_time, usr, clu) SELECT NULL, NOW(), " . $usr . ", " . $clu . " FROM DUAL WHERE (SELECT COUNT(*) FROM fa_use_clu WHERE usr=" . $usr . " AND clu=" . $clu . ") < 1";
Now, as I'm trying to use JDatabaseQuery methods, how the above mentioned query could be transformed correctly?
I have checked this link, which is from the official documentation, but seems I cannot find an appropriate solution.
Any ideas?
Thanks!

Related

Wordpress and MySQL, putting a column of results into an array

I have a column in MySQL in the following format after I run a certain $sql:
colname
12
15
10
23
12
2
What I want is to transfer this into
$colname = array(12,15,10,23,12,2)
I came up with:
$results = $wpdb->get_results($sql);
$colname=array();
foreach($results as $result){
$colname[] = $result;}
Is this the most efficient way? The order is also very important
You can probably use something like:
$sql =
"SELECT " .
" group_concat(colname ORDER BY order_by SEPARATOR ',') AS txt_result " .
"FROM " .
" t ; " ;
$results = $wpdb->get_results($sql);
$colname = split(',', $results[0]['txt_result'])
Note that you need a certain ORDER BY expression. By default, SQL does not provide any determined order. $colname will be an array of textual representations of your numbers. You should convert them to numbers if need to.
See the result of the SQL query at dbfiddle here
Reference:
GROUP_CONCAT()

How to add 'AND' parts to Joomla Jdatabase query?

I need to write an db query based on the Joomla jdatabase format, but I get stuck with writing the 2 'AND' parts for the native sql query below (I could not figure it out based on http://docs.joomla.org/Selecting_data_using_JDatabase).
How to include the 2 AND parts? Appreciate your help
//get userid of collective based on entered collective name, and get productid based on entered productname
//NATIVE MYSQL:
SELECT #__users.id, #__products.productid
FROM #__users INNER JOIN #__products
ON #__users.id = #__products.owner
AND #__users.name = $form_username
AND #__products.productname = $form_productname;
What I have sofar:
//Joomla Jdatabase query sofar:
$query
->select($db->quoteName(array('a.id', 'b.productid')))
->from($db->quoteName('#__users', 'a'))
->join('INNER', $db->quoteName('#__products', 'b') . ' ON (' . $db->quoteName('a.id') . ' = ' . $db->quoteName('b.owner') . ') ') //HERE I think some AND parts need to be included in some way?
->order($db->quoteName('a.created') . ' DESC');
I haven't tested this so please let me know if it works and if not, I will come back with an edit
->join('INNER', $db->quoteName('#__products', 'b') . ' ON (' . $db->quoteName('a.id') . ' = ' . $db->quoteName('b.owner') . ')
AND ' . $db->quoteName('#__users.name') . ' = ' . $form_username . '
AND ' . $db->quoteName('#__products.productname') . ' = ' . $form_productname)

Truncating a SQL char value

I hope that someone can tell me what I am doing wrong.
I would like to query my SQL table and receive back a ClassID and a ClassName.
The ClassID is a char(8) and holds values such as 123.45L1 or 350.12.
I am attempting to shorten that value so that I receive back 123 or 350 only.
Here is my code:
$classSelect = "SELECT LEFT(ClassID , 3), ClassName FROM Class GROUP BY ClassID";
$result = mysql_query($classSelect);
echo "<td><select multiple size='10' name='Class'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='Choice'" . $row['ClassID'] . " - " . $row['ClassName'] . "'>" . $row['ClassID'] . " - " . $row['ClassName'] . "</option>";
}
echo "</select></td>";
SELECT LEFT(ClassID , 3) AS somename, ClassName
and then refer it from PHP as $row['somename']
If you are seeking to extract the string up to the decimal point, and that might not always be in the same place, you can use MySQL's SUBSTRING_INDEX() function:
SELECT SUBSTRING_INDEX(ClassID, '.', 1) FROM Class
If you are seeking to extract the integer up to the first non-decimal character, you can simply CAST() the string and MySQL will do the rest:
SELECT CAST(ClassID AS UNSIGNED) FROM Class
The benefit of this latter approach is that the resulting column will be of the correct datatype.

Maybe TIMEDIFF function in sql is not accepting column name as one of the parameters

My requirement is to pull records from mysql database which have just 5 mins left from the current time as per the one of the columns in the database. The column is has user inserted datetime.
date_default_timezone_set("UTC");
$utc_time = date("Y-m-d H:i:s", time());
echo "UTC Time: " . $utc_time . "<br>";
$result = mysql_query("select reminder_text, reminder_subject, reminder_date_time_utc $table_name where (TIME_TO_SEC (TIMEDIFF(reminder_date_time_utc , '$utc_time')) < 300) AND (TIMEDIFF(reminder_date_time_utc , '$utc_time')) > 0) ") or die(mysql_error());
here the reminder_date_time inside the TIMEDIFF function is the column name to pick up the DATETIME. Using this query I do not get the results but if I place the date instead of reminder_date_time it gives me the correct output. For example if I say TIMEDIFF('2013-07-12 11:05:00' , '$utc_time') it gives me the correct output. And this same value: 2013-07-12 11:05:00 is actually present in one of the rows of this column reminder_date_time_utc
Any advice where I am going wrong... Does TIMEDIFF function not accept column name as one of the parameters.
Do you forgot the FROM in your sql?
Why dont you try to do it like following:
$utc_time = date("Y-m-d H:i:s", time() - 30000);
and change the query to
'SELECT * FROM ' . $tablename . ' WHERE reminder_date_time_utc > "' . $utc_time . '"';
or use DATE_ADD() function :
'SELECT * FROM ' . $tablename . ' WHERE reminder_date_time_utc > DATE_ADD(NOW(), INTERVAL -'5' SECOND));

Is there any mysql/Oracle function to give incremental no. to one column on the basis of another columns of similar values?

I am interested to know that Is there any mysql/Oracle function to give incremental no. to one column on the basis of another columns of similar values?
Like in my below code, I have order_primary column which contains order no. so based on that we can identify how many products belongs to particular order. Also count is for storing those values like 1,2,3 etc.
But I am facing problem that count value is just going incrementaing...
My code-:
$query_product = "SELECT name, id,qty_ordered,price,row_total,base_subtotal,
base_shipping_amount,base_grand_total,order_primary,message
FROM sales_order WHERE `prod_Flag`=0 ";
$result_query_product = mysql_query($query_product);
$count = 0;
while($row = mysql_fetch_array($result_query_product))
{
$count++;
$name = ($row["name"]);
$message1 = ($row["message"]);
$result_str_product .= "('". mysql_real_escape_string($name) . "',". "'" . $row["sku"] . "'," . "'" . $row["qty_ordered"] . "',". "'" . $row["price"] . "'," . "'" . $row["row_total"] . "'," . "'" . $row["base_subtotal"]. "'," . "'" . $row["base_shipping_amount"] . "'," . "'" . $row["base_grand_total"] ."',". $row["order_primary"].",". $count.",". "'".mysql_real_escape_string($message1)."'".", NOW()),";
}
$query_prod_insert = "INSERT into sales_product(name, sku, qty_ordered, price, row_total, base_subtotal, base_shipping_amount,base_grand_total,prod_foreign,count,message,product_creation_date) VALUES ".$result_str_product;
$final_query = substr_replace($query_prod_insert,";",-1);
$result_query_product_outbound = mysql_query($final_query);
So My o/p is-:
('shirt','st','2.0000','75','150','150','20','170',29,1,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,2,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,3,NOW()),
('socks','sk','5.0000','20','100','100','05','105',30,4,NOW());
('jackt','jt','3.0000','40','120','120','15','135',30,5,NOW());
But I want o/p like this-:
('shirt','st','2.0000','75','150','150','20','170',29,**1**,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,**2**,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,**3**,NOW()),
('socks','sk','5.0000','20','100','100','05','105',30,**1**,NOW());
('jackt','jt','3.0000','40','120','120','15','135',30,**2**,NOW());
So Is there any mysql/Oracle function to give incremental no. to one column on the basis of another columns of similar values i.e. in my case, for same order no. value say 29, count values should be 1,2,3 & for same order no. 30, count value should be 1,2...
So is there any function or how to do the same.
For Oracle this is pretty easy:
SELECT order_no,
row_number() over (partition by order_no order by order_primary) as rn
FROM sales_product
Note: I'm guessing the column names as they are somewhere hidden in the PHP(?) code. Please adjust them according to your table structure. For future posts you should also include the corresponding CREATE TABLE statement in your question.