因此,第一次运行它时,输出是添加了数据,第二次运行时,输出是存在的数据,如果我将值更改为888和999,但仍将其插入表中怎么办?因为将来值会回到123和456。谢谢,如果有人纠正我的问题,我将不胜感激
<?php
$conn = mysqli_connect('localhost', 'root', '', 'database') or die('Error connecting to MySQL server');
$check=mysqli_query($conn,"SELECT col1, col2 FROM mytable");
$checkrows=mysqli_num_rows($check);
if ($checkrows > 0)
{
echo "<br>data exists";
}
else
{
$sql = "INSERT INTO mytable (`col1`, `col2`) VALUES ('123', '456')";
$conn->query($sql);
echo "<br>data added";
}
?>
答案 0 :(得分:0)
在$ check变量中,您也要进行查询,以查看是否已写入数据,因此缺少WHERE元素,在FROM表中,您需要添加WHERE col1 ='888'AND col2 =' 999'
答案 1 :(得分:0)
如果您是第一次添加123和456,现在想添加888和999,请执行以下操作。
<?php
$col1 = 888;
$col2 = 999;
$conn = mysqli_connect( 'localhost', 'root', '', 'database') or die('Error connecting to MySQL server' );
$sql_query = " SELECT col1, col2 FROM mytable where ( col1 = $col1 and col2 = $col2 )"
$check = mysqli_query( $conn, $sql_query );
$checkrows = mysqli_num_rows( $check );
if ( $checkrows > 0 ) {
echo "<br>data exists";
} else {
$sql = " INSERT INTO mytable ( `col1`, `col2` ) VALUES ( $col1, $col2 )";
mysqli_query($conn, $sql );
echo "<br> data added ";
}
?>