Home > Backend Development > PHP Tutorial > PHP connects to MYSQL database

PHP connects to MYSQL database

WBOY
Release: 2016-07-29 09:06:05
Original
1055 people have browsed it

Because a certain project required PHP to connect to MySql two days ago. Although I learned it before, I have basically forgotten it now. However, I later found a method by searching a lot of information:

<?<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>?>
Copy after login

The above introduces PHP to connect to the MYSQL database, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template