I have Date and Time fields stored on mysql database, which have a very ugly unix format (applied by mysql).
In order to adapt this format to a more familiar one and echo it on the screen, I would fetch the date and bind it to a variable $mydate, so then I just format it this way.
$mydate= new DateTime($mydate);
$mydate=date_format($mydate,"d/m/Y");
This works perfect for me.
Now I have a new challenge: I want to build a table in which I have a Date and Time fields which I have to format somehow too. So hereĀ“s my code till now:
if ($arch = $pdo->prepare("SELECT date, time, info FROM tblinfo WHERE idinfo = ?")) {
$arch ->execute(array($idpac));
$data = $arch->fetchAll();
echo '<div class="cool_table" ><table><tr><td>TIME</td><td >DATE</td><td>INFO</td></tr>';
foreach ($data as $row){
echo '<tr>';
foreach ($row as $col){
echo '<td>'.$col.'</td>';
}
echo '</tr>';
}
echo '</table></div>';
}
So this generates a very cool table for me. But I cant seem to figure out how can I format the Date and Time using this code. Can someone help me with this one?
I recommend you format the date directly in the query, e.g.:
SELECT
DATE_FORMAT(date,'%m/%d/%Y') AS formateddate,
TIME_FORMAT(time,'%H:%i') AS formatedtime,
info
FROM tblinfo
WHERE idinfo = ?
EDIT
swapped arguments as from comment by #azirion
Have you tried googling LANGUAGE OBJECT OPERATION which yields PHP DateTime Format, and returns as one of the first results:
http://php.net/manual/en/datetime.format.php
Is that page any help? The technique generalizes. :)
Related
I am wanting to count all occurrences of the # symbol in a field and originally i thought LIKE '%#%' would be the way to go, but if the character appears in the field more than once it only counts it as one.
What other method are there that i could use that would count every occurrence?
Thanks.
EDIT
For anyone needing it, this is what i ended up using that works.
$count = 0;
$sql = mysql_query("SELECT LENGTH(field_name) - LENGTH(REPLACE(field_name,'#','')) AS 'occurs' FROM table_name WHERE field_name LIKE '%#%'");
while ($data = mysql_fetch_assoc($sql)) {
$count += $data['occurs'];
}
echo $count;
select length('aa:bb:cc:dd')-length(replace('aa:bb:cc:dd',':',''));
source: http://lists.mysql.com/mysql/215049
You could make this even simpler by using the ``substr_count function in php. see below.
$message = $row['themessage'];
echo substr_count($message, '#');
what this will return is the number of times # has occurred in your "themessage" field in your database.
i have question i don't know better approach to do it in mysql. I have a table in mysql with list of regex's each regex represent a company order number
i want to be able to compare a number to that list to get which company this number belongs to. the lazy way is to list all the regex in php and then using loop to get the company , but i want to do this using the power of mysql .
Like #Mech mention this might be vague.
i will try to explain it more :
I have two tables table with actual regex pattern in plain text in a column like "^[8]{1}[0-9]{10}$"
and this pattern belong to a company , there is more than 500 regex patterns .
Thank you.
Here you go #BM2ilabs. A function as requested :)
carrierID(88888141234);
function carrierID($ordernum) {
// create a connection to your db here
// fetch data needed for loop
$sql = "SELECT regex, carrier_id FROM `company_tbl_from_image`";
// fetch results
$results = $conn->query($sql);
// loop through $results
foreach ($results as $result) {
// individually check against each regex in the table
$regex = $result[regex];
// find first instance of $regex, where the $ordernum is unique, there should only be one match
if (preg_match('/'.$regex.'/', $ordernum)) {
$carrier_id = $result[carrier_id];
break; // remove break to show other matches
}
}
// check if $carrier_id is empty
if ($carrier_id <> "") {
echo $carrier_id;
} else {
echo "No carrier ID found.";
}
}
MySQL only option. Just search this:
SELECT carrier_id FROM `company_tbl_from_image` WHERE 'order number' REGEXP regex
I have a MySQL connection with powershell that returns string values. It iterates through the return just fine- without my connection info here is the simple return (0....4) are the colums to return based off MySQL query:
$dr3.GetString(0)
$dr3.GetString(1)
$dr3.GetString(2)
$dr3.GetString(3)
$dr3.GetString(4)
My question is how to iterate through these results to generate a email report. The results return- this works great. For the sake of example say each of the above strings return 5 rows. I want to display these five rows in a table (hash or convertto-html or other...) and pass the "variable" of the new element/hash to a send-mailmessage command to generate a daily emailed report. So far I can only get the first return to print- e.g. $dr3.GetString(0) prints "Dave". I can get the first row of every column to print fine to a variable but am wondering if I am missing a foreach loop coupled with a convertto-html table in here somewhere....I know there must be something with iteration and convertto-html that I am missing! Thanks in advance!
Found the answer that works for my use case. Instead of using convertto-html, I am just using html fragmenting and string pasting. Below is my code and this works like a charm:
while ($dr3.Read())
{
$dr3.GetString(0)
$dr3.GetString(1)
$dr3.GetString(2)
$dr3.GetString(3)
$dr3.GetString(4)
#build html table foreach array
$html = "<table><tr><td>First Name</td><td>Last Name</td></tr>"
foreach ($result in $dr3)
{
$html += "<tr><td>" + $dr3.GetString(0) + "</td><td>" + $dr3.GetString(1) + "</td></tr>"
}
$html += "</table>"
This is sort of a roundabout way of getting there....but this works. Thanks for the ideas- they got the wheels turning Mike.
I have a query:
"SELECT Time, Date, Name, Email FROM table"
It converts the results to json to be passed via ajax, the problem is I want a new column in the sql, so I add it to the query:
"SELECT Time, Date, Name, Email, Address FROM table"
now the json encode does not work, I have tried changing data types and using UTF-8 however this did not work, none of the others are using UTF-8 but still work anyway, Thanks.
This is my code to encode to json which does work until I add the new collumn from sql
if ($result = $mysqli->query($query)) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
Solved
The problem was the last column i was trying to get was called "Show" for some reason sql does not like this, i renamed this column to "lol" (temporary) and it works!
I expect this is a simple coding error.
When trying to get all results from database table, the first result is always missed off. Even when adding and removing information to the database it will always miss off the result with the lowest ID.
$data = mysql_query("SELECT * FROM tbl_messages")
or die(mysql_error());
$info = mysql_fetch_array( $data );
while($info = mysql_fetch_array( $data ))
{
Print "" .$info['subject']. "";
echo "<hr>";
}
Your current code calls mysql_fetch_array and assigns the result (the first row of the result set) to $info. You don't do anything with $info, and in the next line you overwrite it with another call to mysql_fetch_array.
You need to delete this line:
$info = mysql_fetch_array( $data );
From the php manual:
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
So after
$data = mysql_query(...) you get an array $data and the internal data pointer points on the first element of $data.
The first call of mysql_fetch_array(...) moves the internal data point ahead, so it now points to the second element.
Then, your while-loop calls mysql_fetch_array(...) AGAIN before issuing the first Print, so the second element gets printed.
You can fix it by removing this line:
$info = mysql_fetch_array( $data );
Remove the first mysql_fetch_array statement.
something like
$data = mysql_query("SELECT * FROM tbl_messages")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "" .$info['subject']. "";
echo "<hr>";
}
You are skipping the first entry by using the code as above.
From mysql_fetch_array
Returns an array that corresponds to the fetched row and moves the
internal data pointer ahead.
Which means that when you get to the while, you have already read the first row, but not used it yet.
I had problems like this too with my table query's ignoring row 0 (the first occurance) and now that I see this I finally understand what's going on.
The clarification is also understandable.
You are asking for a query_fetch_array and you put what it finds in $info. This seems ok. Next you ask for the remaining rows, since you just removed one row from the possible returns, it also works perfectly.
Remove this line:
$info = mysql_fetch_array( $data );
and you get all your rows from your table. Or, if you are wondering, ECHO the $info before your while loop in the fashion you are printing or just try var_dumping it.