首頁 > 後端開發 > php教程 > PHP連接MYSQL資料庫

PHP連接MYSQL資料庫

WBOY
發布: 2016-07-29 09:06:05
原創
1054 人瀏覽過

因為前兩天某項目需要PHP連接MySql,雖然以前學過,但是現在基本上也忘得一干二淨了,不過後來查找大量資料找到了方法:

<?<span>php
    </span><span>//</span><span>设置字符集</span><span>header</span>('Content-Type: text/html; charset=utf8'<span>);

    </span><span>//</span><span>连接数据库</span><span>$link</span> = <span>mysql_connect</span>("localhost","root","123456"<span>);

    </span><span>if</span>(!<span>$link</span><span>){
        </span><span>echo</span> '数据库连接失败...<br>'<span>;
        </span><span>exit</span>(-1<span>);
    }</span><span>else</span><span>{
        </span><span>echo</span> "数据库连接成功...<br>"<span>;
    }

    </span><span>//</span><span>选择一个数据库作为默认数据库</span><span>mysql_select_db</span>('php_sjk'<span>);

    </span><span>//</span><span>执行sql插入语句</span><span>$sql</span> = "INSERT INTO zh VALUES (NULL,'王杰','123456')"<span>;
    </span><span>$cr</span> = <span>mysql_query</span>(<span>$sql</span><span>);

    </span><span>//</span><span>判断是否插入成功</span><span>if</span>(!<span>$cr</span><span>){
        </span><span>echo</span> "数据插入失败。<br>"<span>;
    }</span><span>else</span><span>{
        </span><span>echo</span> "数据插入成功。<br>"<span>;
    }
    
    </span><span>//</span><span>执行sql查询语句</span><span>$sql</span> = "select * from zh"<span>;
    </span><span>$cr</span> = <span>mysql_query</span>(<span>$sql</span><span>);
    
    </span><span>//</span><span>得到返回的结果集,并循环输出</span><span>echo</span> "数据展示:<br><br><br>"<span>;
    </span><span>while</span>(<span>$a</span> = <span>mysql_fetch_row</span>(<span>$cr</span><span>)){
        </span><span>echo</span> "{<span>$a</span>[0]}——{<span>$a</span>[1]}——{<span>$a</span>[2]}<br>"<span>;
    }

    </span><span>//</span><span>关闭数据库连接</span><span>mysql_close</span>(<span>$link</span><span>);
</span>?>
登入後複製

以上就介紹了PHP連結MYSQL資料庫,包括了方面的內容,希望對PHP教學有興趣的朋友有幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板