将 PHP 变量传递给 MySQL [英] Passing PHP variables into MySQL

查看:41
本文介绍了将 PHP 变量传递给 MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP 中有一个函数可以将值插入到 MYSQL 表中.

I have a function in PHP which inserts values into MYSQL tables.

function insertRow($db, $new_table, $ID, $Partner, $Merchant)
{
    $insert = "INSERT INTO " .$new_table. " VALUES(number, "string", "string")"
    $q = mysqli_query($db, $insert);
}

我正在努力定制 VALUES 部分.我需要数字、字符串和字符串分别是 PHP 中的 ID、合作伙伴和商家变量.

I am struggling customizing the VALUES part. I need the number, string, and string to be ID, Partner, and Merchant variables from PHP respectively.

我试过了

function insertRow($db, $new_table, $ID, $Partner, $Merchant)
{
    $insert = "INSERT INTO " .$new_table. " VALUES(" .$ID . $Partner . $Merchant . ")";
    $q = mysqli_query($db, $insert);
}

也是.但它似乎不起作用,因为对于 SQL,字符串值必须用引号括起来.但是,如果我更改代码使其 ."$ID" .$合作伙伴".$商家".")";因此变量根据需要用引号引起来,它们不再是 PHP 变量.如何让我的 PHP 变量包含在引号中,以便我可以正确执行 SQL?

as well. But it doesn't seem to work because for SQL the string values must be surrounded with quotes. But if I change the code so that its ."$ID" . "$Partner" . "$Merchant" . ")"; and thus the variables are in quotes as needed, they are no longer PHP variables. How do I get my PHP variables to be included in quotes so that I can execute the SQL correctly?

推荐答案

使用串联的其他答案很简单.最好的方法是使用准备好的语句,这将使您的代码更加安全.

The other answers, using concatenation, are the simple ones. The best one is to use prepared statements, which will make your code significantly more secure.

$insert = "INSERT INTO " .$new_table. " VALUES(?, ?, ?)";
$q = mysqli_prepare($db, $insert);
mysqli_stmt_bind_param($q, "iss", $ID, $Partner, $Merchant);
mysqli_stmt_execute($q);

进行参数化查询意味着您的查询和数据是分开发送的.这意味着查询的结构已经存在,因此不能被数据中插入的任何其他内容更改,这意味着您可以避免 SQL 注入.

Doing parameterised queries means your query and the data are sent separately. This means that the structure of the query already exists, and so cannot be altered by anything else inserted in the data, which means you are safe from SQL injection.

参见 PHP 手册:

这篇关于将 PHP 变量传递给 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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