-
Notifications
You must be signed in to change notification settings - Fork 5
/
stackoverflow.php
1864 lines (1597 loc) · 57.6 KB
/
stackoverflow.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
$ch = curl_init();
$timeout = 300;
$useragent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
$header = array(
'Accept-Language: zh-cn',
'Connection: Keep-Alive',
'Cache-Control: no-cache',
'Content-Type: Application/json;charset=utf-8'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = '{"arr":"{\"id\":\"7fce678b6db1f3152479b259222beede\",\"imp\":[{\"id\":\"ffe00609f6004839d907e318db2a5dce\",\"banner\":{\"w\":200,\"h\":100},\"tagid\":\"fccb1731f90438afd6b1a44db0779500\"}],\"user\":{\"id\":\"\"},\"device\":{\"ip\":\"172.20.207.39\"}}"}';
// $data_string['data'] = $json;
// $data = http_build_query($data_string);
// echo $data;
curl_setopt($ch, CURLOPT_URL, 'http://www.vhallapp.com/getjson.php');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$body = curl_exec($ch);
echo '<pre>';print_r($body);
$itemCount = 1;
echo 'You have ordered ', $itemCount, ' item', $itemCount === 1 ? '' : 's';
// http://stackoverflow.com/documentation/php/194/variables ↑ ↑ ↑ - Note the commas
#> "You have ordered 1 item"
$x=1;$y=2;
echo "The total is: " . ($x + $y);
echo "The total is: ", $x + $y;
function say_hello() {
return "Hello!";
};
echo "I say: {say_hello()}";
#> "I say: {say_hello()}"
class Person {
function say_hello() {
return "Hello!";
}
}
$max = new Person();
echo "Max says: {$max->say_hello()}";
#> "Max says: Hello!"
// Example of invoking a Closure — the parameter list allows for custom expressions
$greet = function($num) {
return "A $num greetings!";
};
echo "From us all: {$greet(10 ** 3)}";
#> "From us all: A 1000 greetings!"
$money = 25.2;
printf('%01.2f', $money);
#> 25.20
$name = 'Jeff';
// The `%s` tells PHP to expect a string
// ↓ `%s` is replaced by ↓
printf("Hello %s, How's it going?", $name);
#> Hello Jeff, How's it going?
// Instead of outputting it directly, place it into a variable ($greeting)
$greeting = sprintf("Hello %s, How's it going?", $name);
echo $greeting;
#> Hello Jeff, How's it going?
echo "<p>We need more ${name}s to help us!</p>";
#> "<p>We need more Joels to help us!</p>"
$myarray = [ "Hello", "World" ];
var_export($myarray);
$array_export = var_export($myarray, true);
printf('$myarray = %s; %s', $array_export, PHP_EOL);
$a = array_fill(5, 6, 'banana');
$array = array(1, 2, 3, 4, 5);
array_walk($array, function(&$value, $key) {
$value++;
});
$res = [];
$array = array(1, array(2, 3, array(4, 5), 6));
array_walk_recursive($array, function(&$value, $key) {
$res[]=$value;
});
// prints "1 2 3 4 5 6"
$json = json_decode('"some string"', true);
var_dump($json, json_last_error_msg());//some string
$json = json_decode('some string', true);#null
$array = ['Joel', 23, true, ['red', 'blue']];
#格式化输出
echo json_encode($array, JSON_PRETTY_PRINT);
echo json_encode($array, JSON_FORCE_OBJECT);
#> {"0":"Joel","1":23,"2":true,"3":{"0":"red","1":"blue"}}
#
#echo json_encode($array, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
var_dump(json_decode('TRUE'), json_last_error_msg());#null
var_dump(json_decode('true'), json_last_error_msg());#true
$array = ['23452', 23452];
echo json_encode($array);
#> ["23452",23452]
echo json_encode($array, JSON_NUMERIC_CHECK);
#> [23452,23452]
$array = ["Singin' in Bahrain", "Charlie Wilson's War"];
echo json_encode($array, JSON_HEX_APOS);
#> ["Singin\u0027 in Bahrain","Charlie Wilson\u0027s War"]
$array = ['filename' => 'example.txt', 'path' => '/full/path/to/file/'];
echo json_encode($array);
#> {"filename":"example.txt","path":"\/full\/path\/to\/file"}
echo json_encode($array, JSON_UNESCAPED_SLASHES);
#> {"filename":"example.txt","path":"/full/path/to/file"}
$array = [5.0, 5.5];
echo json_encode($array);
#> [5,5.5]
#echo json_encode($array, JSON_PRESERVE_ZERO_FRACTION);
#> [5.0,5.5]
$jsonString = json_encode("{'Bad JSON':\xB1\x31}");
if (json_last_error() != JSON_ERROR_NONE) {
printf("JSON Error: %s", json_last_error_msg());
}
#> JSON Error: Malformed UTF-8 characters, possibly incorrectly encoded
#http://stackoverflow.com/documentation/php/617/json/18990/header-json-and-the-returned-response
class MathValues {
const PI = 3.14159;
const PHI = 1.61803;
const LABOR_COSTS = 12.75 * 0.26;
}
$radius=2;
$area = MathValues::PI * $radius * $radius;
// class_exists(ThisClass\Will\NeverBe\Loaded::class, false);
#namespace foo;
#use bar\Bar;
#echo json_encode(Bar::class); // "bar\\Bar"
#echo json_encode(Foo::class); // "foo\\Foo"
#echo json_encode(\Foo::class); // "Foo"
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$pdo = new PDO(
$dsn,
'root',
null,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
#http://stackoverflow.com/documentation/php/275/using-a-database
try {
$pdo->beginTransaction();
$statement = $pdo->prepare("UPDATE app_ad SET name = 1");
$statement->execute();
$statement = $pdo->prepare("UPDATE app_ad SET url = 2");
$statement->execute();
$pdo->commit();
} catch (\Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollback();
// If we got here our two data updates are not in the database
}
throw $e;
}
$uppercase = function($data) {
return strtoupper($data);
};
$mixedCase = ["Hello", "World"];
$uppercased = array_map($uppercase, $mixedCase);
class SomeClass {
public function __invoke($param1, $param2) {
echo 'method';
}
}
$instance = new SomeClass();
$instance('First', 'Second'); // call the __invoke() method
if (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
// http://stackoverflow.com/documentation/php/1687/operators
// http://stackoverflow.com/documentation/php/1687/operators/5451/altering-operator-precedence-with-parentheses
// $name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';
// $name = $_POST['name'] ?? 'nobody';
// usort($list, function($a, $b) { return $a->weight <=> $b->weight; });
// usort($list, function($a, $b) {
// return $a->weight < $b->weight ? -1 : ($a->weight == $b->weight ? 0 : 1);
// });
#echo '<?php var_dump($argv);' | php
#php -r 'var_dump($argv);'
$output = `ls`;
echo "<pre>$output</pre>";
// $name = readline("Please enter your name:");
print "Hello, {$name}.";
function get_client_ip ()
{
// Nothing to do without any reliable information
if (!isset ($_SERVER['REMOTE_ADDR'])) {
return NULL;
}
// Header that is used by the trusted proxy to refer to
// the original IP
$proxy_header = "HTTP_X_FORWARDED_FOR";
// List of all the proxies that are known to handle 'proxy_header'
// in known, safe manner
$trusted_proxies = array ("2001:db8::1", "192.168.50.1");
if (in_array ($_SERVER['REMOTE_ADDR'], $trusted_proxies)) {
// Get IP of the client behind trusted proxy
if (array_key_exists ($proxy_header, $_SERVER)) {
// Header can contain multiple IP-s of proxies that are passed through.
// Only the IP added by the last proxy (last IP in the list) can be trusted.
$client_ip = trim (end (explode (",", $_SERVER[$proxy_header])));
// Validate just in case
if (filter_var ($client_ip, FILTER_VALIDATE_IP)) {
return $client_ip;
} else {
// Validation failed - beat the guy who configured the proxy or
// the guy who created the trusted proxy list?
// TODO: some error handling to notify about the need of punishment
}
}
}
// In all other cases, REMOTE_ADDR is the ONLY IP we can trust.
return $_SERVER['REMOTE_ADDR'];
}
print get_client_ip ();
$a = 1;
$b = 1;
$a = $b += 1;#2,2
$a = 3;
$b = ($a = 5);#5,5
$e = false || true;// true.
$e = false or true;// false.
#It's because $e = false || true is evaluated as $e = (false || true) and
#$e = false or true is evaluated as ($e = false) or true
#Because of this it's safer to use && and || instead of and and or.
$string = $_REQUEST['user_comment'];
if (!mb_check_encoding($string, 'UTF-8')) {
// the string is not UTF-8, so re-encode it.
$actualEncoding = mb_detect_encoding($string);
$string = mb_convert_encoding($string, 'UTF-8', $actualEncoding);
}
$i = 1;
while ($i < 10) {
echo $i;
$i++;
}
const APP_LANGUAGES = ["de", "en"]; // arrays
$constants = get_defined_constants();
define("HELLO", "hello");
define("WORLD", "world");
if (defined("GOOD")) {
print "GOOD is defined"; // doesn't print anyhting, GOOD is not defined yet.
}
defined("PI") || define("PI", 3.1415); // "define PI if it's not yet defined"
$new_constants = get_defined_constants();
$myconstants = array_diff_assoc($new_constants, $constants);
var_export($myconstants);
/*
Output:
array (
'HELLO' => 'hello',
'WORLD' => 'world',
)
*/$ip = gethostbyname ( 'www.example.com' );
#http://curl.haxx.se/docs/caextract.html
#curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
#curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
class Example2
{
private $hook = "phpinfo();";
}
$num = 10;
switch(true) {
case ($num % 2 == 0):
echo "I was divided by 2..";
break;
}
print urlencode(serialize(new Example2));
$url = 'https://example.org/foo/bar';
if (!headers_sent()) { // check headers - you can not send headers if they already sent
// header('Location: ' . $url);
// exit; // protects from code being executed after redirect request
} else {
// throw new Exception('Cannot redirect, headers already sent');
}
$url = 'http://www.example.com/page?foo=1&bar=baz#anchor';
$queryString = parse_url($url, PHP_URL_QUERY);
$doc = new DOMDocument();
// $doc->loadXML($string);
$string = "<p>Example</p>";
$newstring = filter_var($string, FILTER_SANITIZE_STRING);
var_dump($newstring); // string(7) "Example"
var_dump(filter_var('joh [email protected]', FILTER_SANITIZE_EMAIL));#[email protected]
$options = array(
'options' => array(
'min_range' => 5,
'max_range' => 10,
)
);
var_dump(filter_var('5', FILTER_VALIDATE_INT, $options));
var_dump(filter_var('10', FILTER_VALIDATE_INT, $options));
var_dump(filter_var('javascript://comment%0Aalert(1)', FILTER_VALIDATE_URL));
// string(31) "javascript://comment%0Aalert(1)"
var_dump(filter_var('96-D5-9E-67-40-AB', FILTER_VALIDATE_MAC));
// Throw an Exception
// throw new Exception("Exception found!"); // Uncaught Exception, script will stop.
// Catch an Exception
try {
throw new Exception("Exception found!");
} catch (\Exception $e) {
echo 'Caught exception: ' . $e->getMessage(); // Caught Exception
// file_put_contents('my_error_log.txt', $ex->getMessage(), FILE_APPEND);
// Script execution continues
} finally {
// This part is always executed, no matter any exception is thrown or not
echo "Reached the finally block!";
}
// system('ls ' . escapeshellarg($_GET['path']);
$date = new DateTime('2008-07-01T22:35:17.02');//new DateTime('@1234567890');
$new_date_format = $date->format('Y-m-d H:i:s');
$now = new DateTime("2016-07-21 02:55:07");
$date = new DateTime();
// $date->setDate(2016, 7, 25);
var_dump($now <= $date); // prints bool(true)
$diff = $now->diff($date);
var_dump($now == $now); // prints bool(true)
$new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');
$timestamp = bcdiv('1234567899000', '1000');
$timestamp = substr('1234567899000', -3);
#http://stackoverflow.com/documentation/php/topics?page=1&tab=popular
#http://stackoverflow.com/documentation/php/205/functional-programming-in-php#t=201609060949099311128
class StaticSquareHolder
{
public static function square($number)
{
return $number * $number;
}
}
$initial_array = [1, 2, 3, 4, 5];
$final_array = array_map(['StaticSquareHolder', 'square'], $initial_array);
// or:
$final_array = array_map('StaticSquareHolder::square', $initial_array); // for PHP >= 5.2.3
var_dump($final_array); // prints the new array with 1, 4, 9, 16, 25
// $final_array = array_map([(new squaredHolder), 'square'], $initial_array);
function isEven($int) {
return ($item % 2) == 0;
}
array_filter($array, 'isEven');
// array_map('strtoupper', $array);
if (!function_exists('codepoint_encode')) {
function codepoint_encode($str) {
return substr(json_encode($str), 1, -1);
}
}
if (!function_exists('codepoint_decode')) {
function codepoint_decode($str) {
return json_decode(sprintf('"%s"', $str));
}
}
#http://stackoverflow.com/documentation/php/4472/unicode-support-in-php#t=201609060941458015713
echo "\nUse JSON encoding / decoding\n";
var_dump(codepoint_encode("我好"));
var_dump(codepoint_decode('\u6211\u597d'));
var_dump('\u6211\u597d');
var_dump(mb_chr(0x010F));
$string = "0| PHP 1| CSS 2| HTML 3| AJAX 4| JSON";
//[0-9]: Any single character in the range 0 to 9
// + : One or more of 0 to 9
$array = preg_split("/[0-9]+\|/", $string, -1, PREG_SPLIT_NO_EMPTY);
//Or
// [] : Character class
// \d : Any digit
// + : One or more of Any digit
$array = preg_split("/[\d]+\|/", $string, -1, PREG_SPLIT_NO_EMPTY);
class Singleton {
public static function getInstance() {
// Static variable $instance is not deleted when the function ends
static $instance;
// Second call to this function will not get into the if-statement,
// Because an instance of Singleton is now stored in the $instance
// variable and is persisted through multiple calls
if (!$instance) {
// First call to this function will reach this line,
// because the $instance has only been declared, not initialized
$instance = new Singleton();
}
return $instance;
}
}
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
// Comparing objects with the '===' operator checks whether they are
// the same instance. Will print 'true', because the static $instance
// variable in the getInstance() method is persisted through multiple calls
var_dump($instance1 === $instance2);
function gen_one_to_three() {
$keys = ["first", "second", "third"];
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $keys[$i - 1] => $i;
}
}
foreach (gen_one_to_three() as $key => $value) {
echo "$key: $value\n";
}
$myClosure = function() {
echo $this->property;
};
class MyClass
{
public $property;
public function __construct($propertyValue)
{
$this->property = $propertyValue;
}
}
$myInstance = new MyClass('Hello world!');
$myBoundClosure = $myClosure->bindTo($myInstance);
$myBoundClosure(); // Shows "Hello world!"
// $myClosure->call($myInstance); //php7 Shows "Hello world!"
//
function createCalculator($quantity) {
return function($number) use($quantity) {
return $number + $quantity;
};
}
$calculator1 = createCalculator(1);
$calculator2 = createCalculator(2);
var_dump($calculator1(2)); // Shows "3"
var_dump($calculator2(2)); // Shows "4"
$array = array(1, 2, 3, 4, 5);
array_walk($array, function(&$value, $key) {
$value++;
});
$array = array(1, array(2, 3, array(4, 5), 6));
array_walk_recursive($array, function($value, $key) {
echo $value . ' ';
});
// prints "1 2 3 4 5 6"
$numbers = [16,3,5,8,1,4,6];
$even_indexed_numbers = array_filter($numbers, function($index) {
return $index % 2 === 0;
}, ARRAY_FILTER_USE_KEY);//16,5,1,6
// print_r(explode(',',$fruits,2)); // ['apple', 'pear,grapefruit,cherry']
// print_r(explode(',',$fruits,-1)); // ['apple', 'pear', 'grapefruit']
$myArray = array(
'foo' => 'bar',
'func' => function($elem) {
echo $elem;
}
);
$myArray['func']('I am a string....cool.');
call_user_func($myArray['func'], 'I am a string....cool.');
$parameters = ['foo' => 'bar', 'bar' => 'baz', 'boo' => 'bam'];
$allowedKeys = ['foo', 'bar'];
$filteredParameters = array_intersect_key($parameters, array_flip($allowedKeys));
// $filteredParameters contains ['foo' => 'bar', 'bar' => 'baz]
$result = array_reduce([10, 23, 211, 34, 25], function($carry, $item){
return $item > $carry ? $item : $carry;//211
});
$result = array_reduce(["hello", "world", "PHP", "language"], function($carry, $item){
return !$carry ? $item : $carry . "-" . $item ;
});//result:"hello-world-PHP-language"
// 所以值大于100http://stackoverflow.com/documentation/php/204/arrays#t=201609060609481550276
$result = array_reduce([101, 230, 210, 341, 251], function($carry, $item){
return $carry && $item > 100;
}, true); //default value must set true
#SELECT * FROM users ORDER BY id ASC LIMIT 0, 2
#SELECT * FROM users ORDER BY id ASC LIMIT 2 默认从0开始
#SELECT * FROM users ORDER BY id ASC LIMIT 2 OFFSET 2 ;limit 2,2
// UPDATE myjson SET dict=JSON_ARRAY_APPEND(dict,'$.variations','scheveningen') WHERE id = 2;
/*
mysql> select @@long_query_time;
+-------------------+
| @@long_query_time |
+-------------------+
| 3.000000 |
+-------------------+
1 row in set (0.02 sec)
SELECT @@slow_query_log; -- Is capture currently active? (1=On, 0=Off)
SELECT @@slow_query_log_file; -- filename for capture. Resides in datadir
SELECT @@datadir; -- to see current value of the location for capture file
SET GLOBAL slow_query_log=0; -- Turn Off
ALTER TABLE your_table_name AUTO_INCREMENT = 101;
http://stackoverflow.com/documentation/mysql/2627/alter-table#t=201609070355296350997
SELECT username FROM users WHERE users LIKE 'admin_';
SELECT st.name,
st.percentage,
CASE WHEN st.percentage >= 35 THEN 'Pass' ELSE 'Fail' END AS `Remark`
FROM student AS st ;
SELECT st.name,
st.percentage,
IF(st.percentage >= 35, 'Pass', 'Fail') AS `Remark`
FROM student AS st ;
mysqladmin -uroot -p<password> drop <db1>
RENAME TABLE `<old name>` TO `<new name>`;
RENAME TABLE `<old db>`.`<name>` TO `<new db>`.`<name>`;
ALTER TABLE fish_data.fish DROP PRIMARY KEY;
SELECT i, RAND() FROM t;
SELECT SQRT(16); -> 4
mysqldump -u root -p --host=localhost --opt --skip-lock-tables --single-transaction \
--verbose --hex-blob --routines --triggers --all-databases |
gzip -9 | s3cmd put - s3://s3-bucket/db-server-name.sql.gz
mysqldump [options] > dump.sql
mysql [options] < dump.sql
SELECT c.CustomerName, COUNT(*) AS 'Order Count'
FROM Customers AS c
INNER JOIN Orders AS o
ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerID;
ORDER BY c.CustomerName;
SELECT c.CustomerName,
( SELECT COUNT(*) FROM Orders WHERE CustomerID = c.CustomerID ) AS 'Order Count'
FROM Customers AS c
ORDER BY c.CustomerName;
SELECT c.CustomerName,
FROM Customers AS c
WHERE EXISTS ( SELECT * FROM Orders WHERE CustomerID = c.CustomerID )
ORDER BY c.CustomerName;
DROP INDEX idx_name ON my_table;
GRANT ALL PRIVILEGES ON my_db.* TO 'my_new_user@localhost' identified by 'my_password';
select '123ABC' * 2;246
SELECT student_name, AVG(test_score) FROM student GROUP BY `group`
$ mysql -uroot -proot test -e'select * from people'
$ mysql -uroot -proot test -s -e'select * from people' > out.txt
$ mysql -uroot -proot test -e'source my_script.sql'
sudo mysqld_safe --skip-grant-tables &
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
FLUSH PRIVILEGES;
ORDER BY FIND_IN_SET(card_type, "MASTER-CARD,VISA,DISCOVER") -- sort 'MASTER-CARD' first.
ORDER BY x IS NULL, x -- order by `x`, but put `NULLs` last.
SELECT * FROM some_table WHERE id IN (118, 17, 113, 23, 72)
ORDER BY FIELD(id, 118, 17, 113, 23, 72);
http://stackoverflow.com/documentation/mysql/1487/delete#t=201609070355267903708
DELETE p2
FROM pets p2
WHERE p2.ownerId in (
SELECT p1.id
FROM people p1
WHERE p1.name = 'Paul')
DELETE p2 -- remove only rows from pets
FROM people p1
JOIN pets p2
ON p2.ownerId = p1.id
WHERE p1.name = 'Paul';
*/
$i = 1;$sum=2;
while ($i<234) {
$sum++;
if ($sum % 2 == 0 || $sum % 3 == 0) {
$i++;
}
}
// http://www.qlcoder.com/task/751e
$num=2;$i=0;$arr=[];
while($num++){
if($num %2==0||$num%3==0){
$i++;$arr[]=$num;
if($i==2332) {
break;
}
}
}
//var_dump($arr);
echo $num.'<br>';echo $i;
$bom = trim($bom, "\xEF\xBB\xBF");
// http://www.thinkphp.cn/code/1423.html
function base64_upload($base64) {
$base64_image = str_replace(' ', '+', $base64);
//post的数据里面,加号会被替换为空格,需要重新替换回来,如果不是post的数据,则注释掉这一行
//PHP解析GET参数时,会经过过滤,即urldecode()处理,而urldecode会解码给出的已编码字符串中的任何 %##。 加号('+')被解码成一个空格字符。
//解决方法:传递参数时,对GET参数进行url编码,注意最好不使用urlencode(),否则会编码空格为+。应参考RFC 1738对url进行编码,使用rawurlencode(),将加号编码为 。这样上面例子中param=abc百分20百分2B,php接收到的param才会是abc +
//另外POST方式会 使用application/x-www-form-urlencoded此编码编码body中的数据,所以不会出现上述例子中的问题。
//字符串base64后传输之前可以先把“+”号替换掉,用“_”,“|”等等都可以,然后另一个页面接收的时候再替换过来即可(str_replace)。最后把替换之后的base64再解码。ok
//https://iyaozhen.com/post-get-urlcode.html
//重定向后的地址中加密后的name参数,其中包含“+”符号,而浏览器的地址栏中碰到“+”符号时会将加号转换为空格,于是要保证base64_decode进行正确的解码操作,我们可以先将参数中的空格替换成加号
////在实际开发中,我们很多时候要构造这种URL,这是没有问题的
$url_decode ="jellybool.com?username=jelly&bool&password=jelly";
/*注意上面两个变量的差别:第一个的username=jellybool,
第二个为username=jelly&bool
这种情况下用$_GET()来接受是会出问题的,这是可以用下面的方法解决
*/
$username="jelly&bool";
$url_decode ="jellybool.com?username=".urlencode($username)."&password=jelly";
//这是可以很好的解决问题
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
//匹配成功
if($result[2] == 'jpeg'){
$image_name = uniqid().'.jpg';
//纯粹是看jpeg不爽才替换的
}else{
$image_name = uniqid().'.'.$result[2];
}
$image_file = "./upload/test/{$image_name}";
//服务器文件存储路径
if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
return $image_name;
}else{
return false;
}
}else{
return false;
}
}
/**
* 对象数组转为普通数组
* JSON字串经decode解码后为一个对象数组,
* 为此必须转为普通数组后才能进行后续处理
* 此函数支持多维数组处理。
*
* @param array
* return array
*/
function objarray_to_array($obj){
$ret = array();
foreach ($obj as $key => $value) {
if (gettype($value) == "array" || gettype($value) == "object") {
$ret[$key] = objarray_to_array($value);
} else {
$ret[$key] = $value;
}
}
return $ret;
}
// php获取一个月的第一天和最后一天
$date = date('Y-m-d H:i:s'); //当前时间
function getthemonth($date)
{
$firstday = date('Y-m-01', strtotime($date));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
return array($firstday, $lastday);
}
$firstday= date('Y-m-d', mktime(0, 0, 0, date('m'), 1));
$lastday =date('Y-m-d', mktime(0, 0, 0,date('m')+1,1)-1);
echo cal_days_in_month(CAL_GREGORIAN,5,2016); //一个月天数,也就是最后一天 第一天 永远是1
echo date('Y-m-t');//最后一天
// ignore_user_abort();
//即使Client断开(如关掉浏览器),PHP脚本也可以继续执行.
set_time_limit(0);
/*$interval=60*5;
do{
$fp= fopen("test.txt","a");
fwrite($fp,"rn".date('Y-m-d H:i:s',time())."rn");
fclose($fp);
sleep($interval);
}while(true);*/
echo '<pre>';
$prize_arr = array(
'0' => array('id' => 1, 'prize' => '一等奖', 'v' => 5),
'1' => array('id' => 2, 'prize' => '二等奖', 'v' => 5),
'2' => array('id' => 3, 'prize' => '三等奖', 'v' => 5),
'3' => array('id' => 4, 'prize' => '四等奖', 'v' => 5),
'4' => array('id' => 5, 'prize' => '五等奖', 'v' => 5),
'5' => array('id' => 6, 'prize' => '六等奖', 'v' => 5),
'6' => array('id' => 7, 'prize' => '七等奖', 'v' => 5),
'7' => array('id' => 8, 'prize' => '八等奖', 'v' => 5),
'8' => array('id' => 9, 'prize' => '九等奖', 'v' => 5),
'9' => array('id' => 10, 'prize' => '十等奖', 'v' => 5),
'10' => array('id' => 11, 'prize' => '十一等奖', 'v' => 25),
'11' => array('id' => 12, 'prize' => '十二等奖', 'v' => 25),
);
foreach ($prize_arr as $k=>$v) {
$arr[$v['id']] = $v['v'];
}
$prize_id = getRand($arr); //根据概率获取奖项id
foreach($prize_arr as $k=>$v){ //获取前端奖项位置
if($v['id'] == $prize_id){
$prize_site = $k;
break;
}
}
$res = $prize_arr[$prize_id - 1]; //中奖项 http://www.thinkphp.cn/code/1240.html
$data['prize_name'] = $res['prize'];
$data['prize_site'] = $prize_site;//前端奖项从-1开始
print_r($data);
// echo getipinfo();
if (get_magic_quotes_gpc()){//magic_quotes_gpc是否为ON
// $value = stripslashes($value);
}
$week_this_monday =strtotime('last Monday'); //本周一
$tomorrow =strtotime("+1 day");//明天
echo $week_last_monday = strtotime('last Monday') - 3600 * 24 * 7; //上周一
echo $week_last_sunday =strtotime('last Monday')- 3600 * 24; //上周日
function getipinfo(){
header("Content-Type:text/html; charset=utf-8");
$url = 'http://1111.ip138.com/ic.asp'; //这儿填页面地址
$info=file_get_contents($url);
$p = "%<center>(.*?)</center>%si";
preg_match_all($p, $info, $arr);
$info=$arr[1];
$str1 = explode("[",iconv('GB2312', 'UTF-8',$info[0]));
$str2 = explode("]",$str1[1]);
$ip=$str2[0].'_'.substr($str2[1],10);
return $ip;
}
// $pic = file_get_contents ( 'php://input' ) ? file_get_contents ( 'php://input' ) : gzuncompress ( $GLOBALS ['HTTP_RAW_POST_DATA'] );
$imgName = time();
$file_dir="images/".$imgName.".jpg";
/*
if($fp = fopen($file_dir,'w')){
if(fwrite($fp,$content)){
fclose($fp);
}
}*/
// var_dump(validateIDCard(''));
//验证身份证是否有效
function validateIDCard($IDCard) {
if (strlen($IDCard) == 18) {
return check18IDCard($IDCard);
} elseif ((strlen($IDCard) == 15)) {
$IDCard = convertIDCard15to18($IDCard);
return check18IDCard($IDCard);
} else {
return false;
}
}
/**
* 获取客户端IP地址
* @return string
*/
function get_client_ip() {
if(getenv('HTTP_CLIENT_IP')){
$client_ip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR')) {
$client_ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR')) {
$client_ip = getenv('REMOTE_ADDR');
} else {
$client_ip = $_SERVER['REMOTE_ADDR'];
}
return $client_ip;
}
/**
* 获取服务器端IP地址
* @return string
*/
function get_server_ip() {
if (isset($_SERVER)) {
if($_SERVER['SERVER_ADDR']) {
$server_ip = $_SERVER['SERVER_ADDR'];
} else {
$server_ip = $_SERVER['LOCAL_ADDR'];
}
} else {
$server_ip = getenv('SERVER_ADDR');
}
return $server_ip;
}
//计算身份证的最后一位验证码,根据国家标准GB 11643-1999
function calcIDCardCode($IDCardBody) {
if (strlen($IDCardBody) != 17) {
return false;
}
//加权因子
$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
//校验码对应值
$code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
$checksum = 0;
for ($i = 0; $i < strlen($IDCardBody); $i++) {
$checksum += substr($IDCardBody, $i, 1) * $factor[$i];
}
return $code[$checksum % 11];
}
// 将15位身份证升级到18位
function convertIDCard15to18($IDCard) {
if (strlen($IDCard) != 15) {
return false;
} else {
// 如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码
if (array_search(substr($IDCard, 12, 3), array('996', '997', '998', '999')) !== false) {
$IDCard = substr($IDCard, 0, 6) . '18' . substr($IDCard, 6, 9);
} else {
$IDCard = substr($IDCard, 0, 6) . '19' . substr($IDCard, 6, 9);
}
}
$IDCard = $IDCard . calcIDCardCode($IDCard);
return $IDCard;
}
// 18位身份证校验码有效性检查
function check18IDCard($IDCard) {
if (strlen($IDCard) != 18) {
return false;
}
$IDCardBody = substr($IDCard, 0, 17); //身份证主体
$IDCardCode = strtoupper(substr($IDCard, 17, 1)); //身份证最后一位的验证码
if (calcIDCardCode($IDCardBody) != $IDCardCode) {
return false;
} else {
return true;
}
}
// 下一篇文章$query = mysql_query("SELECT id,title FROM article WHERE id>'$id' ORDER BY id ASC LIMIT 1");
// $next = mysql_fetch_array($query);
#TODO case:http://www.thinkphp.cn/code/1427.html
$aData = array(
array('id'=>1,'name'=>'名称1'),
array('id'=>2,'name'=>'名称2'),
array('id'=>3,'name'=>'名称3'),
);
$aTitle = array(
array('id','标记'),
array('name','名称'),
);
// exportCSV($aData, $aTitle);
function exportCSV($aData = [], $aTitle = [], $sFileName=false)
{
if (!is_array($aData) || !is_array($aTitle))
return false;
if (empty($aData) || empty($aTitle))
return false;
$sFileName = $sFileName ? mb_convert_encoding($sFileName, "GB2312", "UTF-8, GB2312") . ".csv": date("_YmdHis") . ".csv";
header('Content-Type: text/csv; CHARSET=gb2312');
header('Content-Disposition: attachment; filename=' . $sFileName);
$output = fopen('php://output', 'w');
for ($i=0;$i<count($aData);$i++) {
for($j=0;$j<count($aTitle);$j++){
$aList[$i][$j] = mb_convert_encoding($aData[$i][$aTitle[$j][0]], "GB2312", "UTF-8, GB2312");
}
}
for ($i=0;$i<count($aTitle);$i++) {
$aTitle[$i] = mb_convert_encoding($aTitle[$i][1], "GB2312", "UTF-8, GB2312");
}
fputcsv($output, $aTitle);
foreach ($aList as $key) {
fputcsv($output, $key);
}
return true;
}
/**
* @name php获取中文字符拼音首字母
* @param $str
* @return null|string
* @author 潘军伟<[email protected]>
* @time 2015-09-14 17:58:14
*/
function getFirstCharter($str)
{
if (empty($str)) {
return '';
}
$fchar = ord($str{0});
if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
$s1 = iconv('UTF-8', 'gb2312', $str);
$s2 = iconv('gb2312', 'UTF-8', $s1);
$s = $s2 == $str ? $s1 : $str;
$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
if ($asc >= -20319 && $asc <= -20284) return 'A';
if ($asc >= -20283 && $asc <= -19776) return 'B';
if ($asc >= -19775 && $asc <= -19219) return 'C';
if ($asc >= -19218 && $asc <= -18711) return 'D';
if ($asc >= -18710 && $asc <= -18527) return 'E';
if ($asc >= -18526 && $asc <= -18240) return 'F';
if ($asc >= -18239 && $asc <= -17923) return 'G';
if ($asc >= -17922 && $asc <= -17418) return 'H';
if ($asc >= -17417 && $asc <= -16475) return 'J';
if ($asc >= -16474 && $asc <= -16213) return 'K';
if ($asc >= -16212 && $asc <= -15641) return 'L';
if ($asc >= -15640 && $asc <= -15166) return 'M';
if ($asc >= -15165 && $asc <= -14923) return 'N';
if ($asc >= -14922 && $asc <= -14915) return 'O';
if ($asc >= -14914 && $asc <= -14631) return 'P';
if ($asc >= -14630 && $asc <= -14150) return 'Q';
if ($asc >= -14149 && $asc <= -14091) return 'R';
if ($asc >= -14090 && $asc <= -13319) return 'S';
if ($asc >= -13318 && $asc <= -12839) return 'T';
if ($asc >= -12838 && $asc <= -12557) return 'W';
if ($asc >= -12556 && $asc <= -11848) return 'X';
if ($asc >= -11847 && $asc <= -11056) return 'Y';
if ($asc >= -11055 && $asc <= -10247) return 'Z';
return null;
}
// $redis=new redis();
// $redis->connect('127.0.0.1','6379');
// print_r($redis->zRevRange('topward100', 0, 4, 'WITHSCORES'));
// Route::get('posts/{post_id}', function ($postId) {
//
// });