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

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

Related

How can I format a number into a currency value without php?

I have a value in my mySQL database 13148.70. I want to convert it into a currency format:
$data = $db->query('SELECT *, ROUND((price), 2) AS price FROM data')->fetchAll(PDO::FETCH_ASSOC);
The result is:
13148.70
But I would need 13 148,70 €
You can use the function money-format in php :money-format
The nearest you can do in mysql would be this :
SELECT *, REPLACE(REPLACE(CONCAT(FORMAT(price, 2)," €"), ",", " "),".",",") AS price FROM data
Syntax
number_format(number,decimals,decimalpoint,separator)
So in your case:
$data = number_format($data, 2, ",", " ");
More information: number_format
Please refer the https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_format
select REPLACE(CONCAT(FORMAT(price,2,'de_DE')," €"),"."," ") from data;

count characters matching in CONCAT MySQL REGEXP

I have the following MySQL query which works
SELECT *,
CONCAT( office, ' ', contactperson ) AS bigDataField
FROM webcms_mod_references
HAVING bigDataField REGEXP "one|two"
Now there is no ORDER BY and if:
- bigDataField contains "one" this field is shown
- bigDataField contains "one two" this field is shown aswell
now it depends on the id which one of those is shown first, but I want the one with the more matches to be shown first!
I tried with
SUM(
CASE WHEN bigDataField REGEXP "one|two"
THEN 1
ELSE 0 END
) AS matches
But that does not work. Can anyone help me. I think the best would be as the title says to count the matching charachters from the REGEXP. If there are other ways please explain.
The REGEXP is a user input, so, I'm trying to implement a small search over a small Database.
This is theoretical whilst sqlfiddle is down but you might have to split the REGEXP into two so you can count the matches. REGEXP will return either a 0 or 1. Either it matched or didn't. There's no support for finding how many times it was matched in a string.
SELECT *,
CONCAT( office, ' ', contactperson ) AS bigDataField
FROM webcms_mod_references
HAVING bigDataField REGEXP "one|two"
ORDER BY (bigDataField REGEXP "one" + bigDataField REGEXP "two") DESC
There is no way to count the amount of matches on a regex. What you can do is match them separately and order by each of those matches. EG:
SELECT *,
CONCAT( office, ' ', contactperson ) AS bigDataField
FROM webcms_mod_references
HAVING bigDataField REGEXP "one|two"
ORDER BY
CASE WHEN bigDataField REGEXP "one" AND bigDataField REGEXP "two" THEN 0
ELSE 1 -- The else should catch the "two" alone or the "one" alone because of the filtering
END
Of course, you can use a LIKE here too but maybe your regex are more complex than that :)
When I want to count some substring I do replace and "-" the length, example:
SELECT (
LENGTH('longstringlongtextlongfile') -
LENGTH(REPLACE('longstringlongtextlongfile', 'long', ''))
) / LENGTH('long') AS `occurrences`
I think this is an elegant solution for a problem of counting how many times 'long' appears inside provided 'string'
This is not especially the answer to this question, but I think strongly attached to it... (And I hope, will help someone, who cames from google, etc)
So if you use PHP (if not, may dont keep reading ...), you can build the query with that, and in this case, you can do this (about #Moob great answer):
function buildSearchOrderBy(string $regex, string $columName, string $alternateOrderByColumName): string
{
$keywords = explode ('|', $regex);
if (empty ($keywords)) {
return $alternateOrderByColumName;
}
$orderBy = '(';
$i = 0;
foreach ($keywords as $keyword) {
$i++;
if ($i > 1) $orderBy .= " + ";
$orderBy .= "IF((" . $columName . " REGEXP '" . $keyword . "')>0, " . (100 + strlen($keyword)) . ", 0)";
}
$orderBy .= ')';
return $orderBy;
}
So in this case every match worth 100 + so many scores, what the numbers of the characters in the current keyword. Every match starting from 100, because this ensure the base, that the first results will be these, where the total score originate from the more matches, but in proportionally worth more a longer keyword in any case.
Builded to one column check, but I think you can update easy.
If copied to your project, just use like this (just an example):
$orderBy = buildSearchOrderBy($regex, 'article.title', 'article.created');
$statement = "SELECT *
FROM article
WHERE article.title REGEXP '(" . $regex . ")'
ORDER BY " . $orderBy . " DESC"
;

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.