create table member(
member_id int not null auto_increment,
member_name varchar(50) not null,
look_contact_number int(4) default 5,
primary key(member_id)
)
create table contact_viewed(
contact_viewed_id int(11) not null auto_increment,
contacted_member_id int (11) not null,
member_id int(11) not null,
primary key(contact_viewed_id)
);
我想在contact_viewed
表中插入member_id
可以相同的数据,这意味着一个成员可以看到多个联系人,但contacted_member_id
应该是唯一的。
我正在使用url的请求参数ID,见下文
/contact_viewed.php?id=1;
首先我已经采取了条件,如果member_id=2
表成员中没有数据然后在表中插入数据,那么我已通过rowCount()
方法检查成员中是否member_id=2
table有数据然后检查contacted_member_id
是否在数据库中可用,如果可用则不执行任何操作,如果不可用则将数据插入数据库。
我的问题是当foreach
循环正在执行时它会将数据插入id != contacted_member_id
,如果有人有想法,请帮助我。
<?php
$stmt7 = $DB_con->prepare ( "SELECT * FROM contact_viewed WHERE member_id=:member_id" );
$stmt7->bindParam ( ":member_id", $m_id );
$stmt7->execute ();
$row2 = $stmt7->fetchAll ();
if ($stmt7->rowCount () > 0) {
foreach ( $row2 as $data ) {
if ($data ['member_id'] == $m_id) {
if($data ['contacted_member_id'] == $_GET['id']){
echo "do nothing1";
}
else{
$stmt6 = $DB_con->prepare ( "INSERT INTO contact_viewed(contacted_member_id,member_id) VALUES(:contacted_member_id,:member_id)" );
$stmt6->bindParam ( ":contacted_member_id", $_GET ['id'] );
$stmt6->bindParam ( ":member_id", $m_id );
$stmt6->execute ();
echo "hello";
}
}
}
}
else{
$stmt6 = $DB_con->prepare ( "INSERT INTO contact_viewed(contacted_member_id,member_id) VALUES(:contacted_member_id,:member_id)" );
$stmt6->bindParam ( ":contacted_member_id", $_GET ['id'] );
$stmt6->bindParam ( ":member_id", $m_id );
$stmt6->execute ();
$available_contact = $userRow ['available_contact'];
$available_contact = $available_contact - 1;
$stmt5 = $DB_con->prepare ( "UPDATE member SET available_contact=:available_contact WHERE member_id=:member_id" );
$stmt5->bindParam ( ":available_contact", $available_contact );
$stmt5->bindParam ( ":member_id", $m_id );
$stmt5->execute ();
echo "ok ok";
}
?>
答案 0 :(得分:1)
试试这个:
<?php
$stmt7 = $DB_con->prepare ( "SELECT * FROM contact_viewed WHERE member_id=:member_id AND contacted_member_id=:contacted_member_id" );
$stmt6->bindParam ( ":contacted_member_id", $_GET ['id'] );
$stmt7->bindParam ( ":member_id", $m_id );
$stmt7->execute ();
$row2 = $stmt7->fetchAll ();
if ($stmt7->rowCount () == 0) {
$stmt6 = $DB_con->prepare ( "INSERT INTO contact_viewed(contacted_member_id,member_id) VALUES(:contacted_member_id,:member_id)" );
$stmt6->bindParam ( ":contacted_member_id", $_GET ['id'] );
$stmt6->bindParam ( ":member_id", $m_id );
$stmt6->execute ();
$available_contact = $userRow ['available_contact'];
$available_contact = $available_contact - 1;
$stmt5 = $DB_con->prepare ( "UPDATE member SET available_contact=:available_contact WHERE member_id=:member_id" );
$stmt5->bindParam ( ":available_contact", $available_contact );
$stmt5->bindParam ( ":member_id", $m_id );
$stmt5->execute ();
echo "ok ok";
}