初学php,于是一开始就在sql(具体点说是mysql)里受挫严重。于是这里记下一些方法。 首先是基本方法。基本方法现在我不用了,所以我就附一下hustoj中的部分吧 基本方法的数据库连接操作: 1 if ( $OJ_SAE ) { // for sae.sina.com.cn 2 mysql_connect (SAE_
初学php,于是一开始就在sql(具体点说是mysql)里受挫严重。于是这里记下一些方法。
首先是基本方法。基本方法现在我不用了,所以我就附一下hustoj中的部分吧
基本方法的数据库连接操作:
<span> 1</span> <span>if</span>(<span>$OJ_SAE</span>) {<span>//</span><span> for sae.sina.com.cn</span> <span> 2</span> <span>mysql_connect</span>(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,<span>SAE_MYSQL_PASS); </span><span> 3</span> <span>$DB_NAME</span>=<span>SAE_MYSQL_DB; </span><span> 4</span> }<span>else</span><span>{ </span><span> 5</span> <span>//</span><span>for normal install</span> <span> 6</span> <span>if</span>(!<span>mysql_pconnect</span>(<span>$DB_HOST</span>,<span>$DB_USER</span>,<span>$DB_PASS</span><span>)) </span><span> 7</span> <span>die</span>('Could not connect: ' . <span>mysql_error</span><span>()); </span><span> 8</span> <span> } </span><span> 9</span> <span>//</span><span> use db</span> <span>10</span> <span>mysql_query</span>("set names utf8"<span>); </span><span>11</span> <span>12</span> <span>if</span>(!<span>mysql_select_db</span>(<span>$DB_NAME</span><span>)) </span><span>13</span> <span>die</span>('Can\'t use foo : ' . <span>mysql_error</span>());
顺带一提,我是通过阅读hustoj的代码入门的php,感谢hustoj这个开源项目。但是我依然想吐槽一下,hustoj的前台代码太烂了。。
这是使用PDO方法操作sql之前的初始化操作。(因为要在SAE上跑所以写了两个)
<span>1</span> <span>//</span><span>db init</span> <span>2</span> <span>if</span> (<span>$ON_SAE</span><span>) { </span><span>3</span> <span>$pdo</span> = <span>new</span> PDO('mysql:host='.SAE_MYSQL_HOST_M.';port='.SAE_MYSQL_PORT.';dbname='.SAE_MYSQL_DB, SAE_MYSQL_USER,<span> SAE_MYSQL_PASS); </span><span>4</span> <span>$pdo</span>->query("set names utf8;"<span>); </span><span>5</span> } <span>else</span><span> { </span><span>6</span> <span>$pdo</span> = <span>new</span> PDO("mysql:host=localhost;dbname=test","root","root"<span>); </span><span>7</span> <span>$pdo</span>->query("set names utf8;"<span>); </span><span>8</span> }
PDO的好处在于防注入的东西。但是也需要一些特别的方法,下面会提及,接下来是操作数据库的例子。
常规方法(依然摘自hustoj的部分代码):
<span>1</span> <span>$sql</span>="SELECT * FROM `mail` WHERE `mail_id`=".<span>$vid</span>." and to_user='".<span>$_SESSION</span>['user_id']."'"<span>; </span><span>2</span> <span>$result</span>=<span>mysql_query</span>(<span>$sql</span><span>); </span><span>3</span> <span>$row</span>=<span>mysql_fetch_object</span>(<span>$result</span>);
处理得到的结果的方式很多样,根据需求实现就是了,这里不再阐述。
同样的部分,换做PDO写法则为:
<span>1</span> <span>$sql</span>=<span>$pdo</span>->prepare("SELECT * FROM `tb_mail` WHERE `mail_id`=".<span>$vid</span>." and to_user='".<span>$_SESSION</span>['UID']."'"<span>); </span><span>2</span> <span>$sql</span>-><span>execute(); </span><span>3</span> <span>$result</span>=<span>$sql</span>->fetchAll();<span>//</span><span>$result[0]['content']</span>
PDO取得的结果的处理方式也很多样,根据需要实现即可。
PDO的好处在于某些时候可以更方便的防止注入等使得数据库接入更安全,方法类似下面这样:
上图是常规做法。
这个是应该改为的做法。
数据库的php接入和操作大致如此,如上仅供参考。如果有新科技的话我会补充进来,如果有错误还请评论指正。