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);
}
I am struggling customizing the VALUES part. I need the number, string, and string to be ID, Partner, and Merchant variables from PHP respectively.
I've tried
function insertRow($db, $new_table, $ID, $Partner, $Merchant)
{
$insert = "INSERT INTO " .$new_table. " VALUES(" .$ID . $Partner . $Merchant . ")";
$q = mysqli_query($db, $insert);
}
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);
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.
See the PHP manual: