我如何正确地检查,看看是否类似的数据是在插入数据库之前,使用foreach循环


How do I properly check to see if similar data is in database before inserting it, using a foreach loop

我想看看我的"invoice_id"变量是否已经在数据库中,然后再插入它。我希望foreach语句循环遍历结果,如果发票Id已经在数据库中,则发出一条语句。

<?php
require("connect.php");
$invoice=$_REQUEST['invoice_id'];
	$sql="SELECT * FROM invoices WHERE id='$invoice'";
	$query=mysqli_query($conn,$sql) or die ("nope");
	$row=mysqli_fetch_array($query);
if(isset($row['id'])){
	$sql3="SELECT * FROM transactions";
	$query3=mysqli_query($conn,$sql3);
	$row3=mysqli_fetch_array($query3);
	
		foreach($row3['invoice_id'] as $value){
			if($value==$invoice){
				echo "That invoice has already been paid";
			}
		}
		
		$invoice_id=$row['id'];
		$mcode=$row['mcode'];
		$rcode1=$row['rcode1'];
		$rcode2=$row['rcode2'];
		$date=date('Y-m-d');
		
		$sql2="INSERT INTO transactions(id,invoice_id,mcode,rcode1,rcode2,date) VALUES('','$invoice_id','$mcode','$rcode1','$rcode2','$date')";
		$query2=mysqli_query($conn,$sql2) or die ("No Connect");
		
		echo "Invoice has been paid!";
	
}
?>	

好了,这是你的第一个问题。

$invoice = $_REQUEST['invoice_id'];
$sql = "SELECT * FROM invoices WHERE id='$invoice'";
https://secure.php.net/manual/en/security.database.sql-injection.php

这是你的问题的外围,所以我对只是发布一个链接没有感到内疚,但是请,为了上帝的爱,阅读并理解它。你发布的代码有一个一英里宽的安全漏洞。这尤其令人担忧,因为你显然是在处理财务数据……

在您的情况下,我可以发送一个请求到您的页面与myfile.php?invoice_id=%27%20OR%20%27%27%3D%27解码为' OR ''='。您的代码将很高兴地在我的"发票ID"中插入,从而产生以下查询:

SELECT * FROM invoices WHERE id='' OR ''=''

由于''总是等于'',您的应用程序将返回数据库中的每个发票。

现在说正题。我假设您在代码中所做的工作比检查已付款/未付款要多,并且发票数据的其余部分是相关的。在这种情况下,您希望使用连接:

// Sanitizing can be as simple as casting to int, although in most cases
// you'd use something like mysqli_escape_string() instead.
$invoice_id = (int) $_REQUEST['invoice_id'];
// LEFT JOIN will make all fields in t[ransactions] available to the query.
//
// If no records in the transactions table satisfy the
// t.invoice_id = i[nvoice].id condition, then all transactions fields will
// be null. So that `t.id IS NOT NULL` will be 1 (true) if there is a
// corresponding transaction, or 0 (false) if there isn't.
//
// You can also add additional conditions to the join, for instance if
// you need to check the transaction status:
// LEFT JOIN transactions AS t ON (t.invoice_id = i.id AND t.status = 'paid')
$sql = "
    SELECT i.*, (t.id IS NOT NULL) AS is_paid FROM invoices AS i
    LEFT JOIN transactions AS t ON t.invoice_id = i.id
    WHERE i.id = $invoice_id
";
$res = mysqli_query($conn, $sql);
if (empty($res) || !$res->num_rows) {
    die('not found');
}
$invoice = $res->fetch_object();
if ($invoice->is_paid) {
    echo "Invoice {$invoice->id} has been paid!";
} else {
    echo "Invoice {$invoice->id} has not been paid!";
}

如果您只想检查发票是否已支付,您可以直接查询事务表:

SELECT * FROM transactions WHERE invoice_id = 123

进一步阅读:

https://dev.mysql.com/doc/refman/5.6/en/join.html

https://en.wikipedia.org/wiki/SQL_injection(再次)