如何使用php连接到MySQL [英] How to connect to MySQL using php

查看:64
本文介绍了如何使用php连接到MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在处理一个使用PHP将电子邮件发送到我的帐户的表单.为了节省空间并使我的邮箱帐户混乱,我现在尝试使用相同的PHP将信息发送到MySQL服务器以记录数据.我一直在尝试使之工作的代码不断出现以下错误:

I have been working on a form that uses PHP to send e-mails to my account. To save room and de-clutter my mailbox account I am now trying to now use the same PHP to send the info to a MySQL server to log the data. The code I have been trying to make work keeps giving the same error of:

不建议使用:mysql_connect():不建议使用mysql扩展,以后将删除

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future

这是我当前尝试使用的PHP代码:

Here is the PHP code that I am currently trying to use:

$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'on-boarding';
mysql_connect($host,$username,$password);
mysql_select_db($dbname);
mysql_query("INSERT INTO  new_employees ('OnBoardedBy', 'EmployeeName', 'HomePhone') VALUES ('$onboarded_by','$employee_name','$home_phone')");

推荐答案

您应使用PDO或MySQLi.我建议直接使用PDO,而不要使用MySQLi. PDO可以更好地集成预准备语句.这样做:

You should use PDO or MySQLi. I'd recommend directly to use PDO and not MySQLi. PDO has a better integration of Prepared Statements. Do it like this:

try {
    $db = new PDO("mysql:host=".$host.";dbname=".$db.";charset=utf8", $user, $password);
} catch(PDOException $e) {
    die("Unable to connect. Error: ".$e->getMessage());
}

$link = $db->prepare("INSERT INTO  new_employees (`OnBoardedBy`, `EmployeeName`, `HomePhone`) VALUES (?, ?, ?)");
$link->bindvalue(1, $onboarded_by);
$link->bindvalue(2, $employee_name);
$link->bindvalue(3, $home_phone);
$link->execute();
$row = $link->fetch(PDO::FETCH_ASSOC);

让我为准备好的查询添加示例.

edit: Let me add an example for a prepared query.

这篇关于如何使用php连接到MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆