Dates in PHP and MySQL_PHP教程
Jul 13, 2016 pm 05:52 PM
I see a lot of people on forums and on my training courses asking about the best way (or any way) to manage dates stored in a MySQL database and used in PHP. Three options follow, but first the problem.
PHP uses unix timestamps for all its date functionality. It has methods to convert these timestamps into pretty much any text format you could want but internally it uses the timestamp format. A timestamp is simply an integer. Specifically, it’s the number of seconds that have elapsed since midnight on January 1st 1970 (greenwich mean time).
MySQL has three date types for use in columns. These are DATETIME, DATE, and TIMESTAMP. DATETIME columns store date and time as a string in the form YYYY-MM-DD HH:MM:SS (e.g. 2006-12-25 13:43:15). DATE columns use just the date part of this format – YYYY-MM-DD (e.g. 2006-12-25). TIMESTAMP columns, despite their name, are nothing like the unix timestamps used in PHP. A TIMESTAMP column is simply a DATETIME column that automatically updates to the current time every time the contents of that record are altered. (That’s a simplification but broadly true and the details are not important here). In particular, since version 4.1 of MySQL the TIMESTAMP format is exactly the same as the DATETIME format.
So the problem is how to work with these two very different date formats – the PHP timestamp integer and the MySQL DATETIME string. There are three common solutions…
One common solution is to store the dates in DATETIME fields and use PHPs date() and strtotime()functions to convert between PHP timestamps and MySQL DATETIMEs. The methods would be used as follows -
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
$phpdate = strtotime( $mysqldate );
Our second option is to let MySQL do the work. MySQL has functions we can use to convert the data at the point where we access the database. UNIX_TIMESTAMP will convert from DATETIME to PHP timestamp andFROM_UNIXTIME will convert from PHP timestamp to DATETIME. The methods are used within the SQL query. So we insert and update dates using queries like this -
$query = "UPDATE table SET
??? datetimefield = FROM_UNIXTIME($phpdate)
??? WHERE...";
$query = "SELECT UNIX_TIMESTAMP(datetimefield)
??? FROM table WHERE...";
Our last option is simply to use the PHP timestamp format everywhere. Since a PHP timestamp is a signed integer, use an integer field in MySQL to store the timestamp in. This way there’s no conversion and we can just move PHP timestamps into and out of the database without any issues at all.
Be aware, however, that by using an integer field to store your dates you lose a lot of functionality within MySQL because MySQL doesn’t know that your dates are dates. You can still sort records on your date fields since php timestamps increase regularly over time, but if you want to use any of MySQL’s date and time functions on the data then you’ll need to use FROM_UNIXTIME to get a MySQL DATETIME for the function to work on.
However, if you’re just using the database to store the date information and any manipulation of it will take place in PHP then there’s no problems. www.2cto.com
So finally we come to the choice of which to use. For me, if you don’t need to manipulate the dates within MySQL then there’s no contest and the last option is the best. It’s simple to use and is the most efficient in terms of storage space in the data table and speed of execution when reading and writing the data.
However, some queries will be more complicated because your date is not in a date field (e.g. select all users who’s birthday is today) and you may lose out in the long run. If this is the case it may be better to use either option 1 or 2. Which of these you use depends on whether you’d rather place the work on MySQL or PHP. I tend to use option 2 but there’s no right or wrong answer – take your pick.
So to summarise, for those who’ve skipped straight to the last paragraph, most of the time I use option 3 but occasionally I use option 2 because I need MySQL to know the field contains a date.
作者:chenjie3392593

Alat AI Hot

Undress AI Tool
Gambar buka pakaian secara percuma

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Clothoff.io
Penyingkiran pakaian AI

Video Face Swap
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Artikel Panas

Alat panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Phpisstillrelevantinmodernenterpriseenvironments.1.modernphp (7.xand8.x) Menawarkan Perpaduan Perlengkapan, ketegangan, jitcompilation, danmodernsyntax, makeitsuatableforlarge-scaleapplications.2.phpintegratefective

Elakkan masalah pertanyaan n 1, mengurangkan bilangan pertanyaan pangkalan data dengan memuatkan data yang berkaitan terlebih dahulu; 2. Pilih hanya medan yang diperlukan untuk mengelakkan memuat entiti lengkap untuk menjimatkan memori dan jalur lebar; 3. Gunakan strategi cache yang munasabah, seperti cache sekunder doktrin atau hasil pertanyaan frekuensi tinggi Cache; 4. Mengoptimumkan kitaran hayat entiti dan panggilan jelas () secara teratur untuk membebaskan memori untuk mengelakkan limpahan memori; 5. Memastikan indeks pangkalan data wujud dan menganalisis penyata SQL yang dihasilkan untuk mengelakkan pertanyaan yang tidak cekap; 6. Lumpuhkan penjejakan perubahan automatik dalam senario di mana perubahan tidak diperlukan, dan gunakan array atau mod ringan untuk meningkatkan prestasi. Penggunaan ORM yang betul memerlukan menggabungkan pemantauan SQL, caching, pemprosesan batch dan pengoptimuman yang sesuai untuk memastikan prestasi aplikasi sambil mengekalkan kecekapan pembangunan.

Untuk membina microservice PHP yang fleksibel, anda perlu menggunakan RabbitMQ untuk mencapai komunikasi asynchronous, 1. Decouple perkhidmatan melalui beratur mesej untuk mengelakkan kegagalan cascade; 2. Konfigurasi beratur berterusan, mesej berterusan, pengesahan pelepasan dan ACK manual untuk memastikan kebolehpercayaan; 3. Menggunakan Backoff Exponential Backoff, TTL dan Kegagalan Pemprosesan Keselamatan Gilir Surat Dead; 4. Gunakan alat seperti penyelia untuk melindungi proses pengguna dan membolehkan mekanisme degupan jantung untuk memastikan kesihatan perkhidmatan; dan akhirnya menyedari keupayaan sistem untuk terus beroperasi dalam kegagalan.

Menggunakan imej asas PHP yang betul dan mengkonfigurasi persekitaran docker yang dioptimumkan prestasi yang selamat adalah kunci untuk mencapai pengeluaran siap. 1. Pilih PHP: 8.3-fpm-alpine sebagai imej asas untuk mengurangkan permukaan serangan dan meningkatkan prestasi; 2. Lumpuhkan fungsi berbahaya melalui php.ini adat, matikan paparan ralat, dan aktifkan Opcache dan JIT untuk meningkatkan keselamatan dan prestasi; 3. Gunakan nginx sebagai proksi terbalik untuk menyekat akses kepada fail sensitif dan memajukan permintaan PHP dengan betul kepada PHP-FPM; 4. Gunakan imej pengoptimuman pelbagai peringkat untuk menghapuskan kebergantungan pembangunan, dan menubuhkan pengguna bukan akar untuk menjalankan bekas; 5. Supervisord pilihan untuk menguruskan pelbagai proses seperti Cron; 6. Sahkan bahawa tiada kebocoran maklumat sensitif sebelum penggunaan

Fail Tetapan.JSON terletak di laluan peringkat pengguna atau ruang kerja dan digunakan untuk menyesuaikan tetapan vscode. 1. Laluan peringkat pengguna: Windows adalah C: \ Users \\ AppData \ Roaming \ code \ user \ settings.json, macOS adalah /users//library/applicationsupport/code/user/settings.json, linux adalah/ 2. Laluan Tahap Ruang Kerja: .VSCODE/Tetapan dalam Direktori Root Projek

Mekanisme pengumpulan sampah PHP didasarkan pada penghitungan rujukan, tetapi rujukan bulat perlu diproses oleh pemungut sampah pekeliling berkala; 1. Rujukan kiraan rujukan segera memori apabila tidak ada rujukan kepada pembolehubah; 2. Rujukan rujukan menyebabkan memori tidak dapat dikeluarkan secara automatik, dan ia bergantung kepada GC untuk mengesan dan membersihkannya; 3. GC dicetuskan apabila zval "akar yang mungkin" mencapai ambang atau panggilan secara manual gc_collect_cycles (); 4. Aplikasi PHP jangka panjang harus memantau gc_status () dan hubungi gc_collect_cycles () dalam masa untuk mengelakkan kebocoran ingatan; 5. Amalan terbaik termasuk mengelakkan rujukan bulat, menggunakan gc_disable () untuk mengoptimumkan bidang utama prestasi, dan objek dereference melalui kaedah CLEAR () ORM.

Bref membolehkan pemaju PHP membina aplikasi yang berskala dan kos efektif tanpa menguruskan pelayan. 1.Bref membawa PHP ke Awslambda dengan menyediakan lapisan runtime PHP yang dioptimumkan, menyokong Php8.3 dan versi lain, dan dengan lancar mengintegrasikan dengan rangka kerja seperti Laravel dan Symfony; 2. Langkah -langkah penempatan termasuk: memasang Bref menggunakan komposer, mengkonfigurasi serverless.yml untuk menentukan fungsi dan peristiwa, seperti titik akhir HTTP dan perintah artisan; 3. Jalankan perintah ServerlessDeploy untuk melengkapkan penggunaan, secara automatik mengkonfigurasi apigeway dan menjana URL akses; 4. Bagi sekatan Lambda, Bref menyediakan penyelesaian.

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha
