检查MySQL表中是否存在值

时间:2015-03-09 15:35:45

标签: php mysql

我是MySQl的新手,我试图检查输入的电子邮件是否与我桌上的任何内容匹配。如果匹配,我需要将电子邮件和同一行的其他列放在另一个表中。

我现在得到的是添加到table2的空白行。

<?php
include "config.php";

$email = $_POST['email'];

$match = mysqli_query("SELECT email FROM table1 WHERE email = $email"); 

if($conn->query($match)){
    //here i have to find the name, school, and grad_year that matches
    // with the email from table 1 which is in the same row. I tried a couple of 
    //things but it didn't work. So i don't know what to put in there.

    $insert = "INSERT INTO table2 VALUES(name,'$email',school,grad year )";

    $conn->query($insert);
}
?>

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

不要永远使用mysql *函数。他们被弃用并且不安全。请改用mysqli *或PDO。请参阅下面的示例代码(我没有运行它并且可能存在错误 - 我的想法是让您走上正确的道路......)

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$email = $_POST['email'];

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM table1 WHERE email=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $email);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    # NOTE: You may prefer $stmt->get_results() and $result->fetch_assoc()
    # to this $stmt->bind_result() and $stmt->fetch().
    $stmt->bind_result($name, $junk, $school, $grad_year);

    /* fetch value */
    if ($stmt->fetch()) {
        $stmt2 = $mysqli->prepare("INSERT INTO table2 VALUES (?,?,?,?)");
        $stmt2->bind_param("ssss", $name, $email, $school, $grad_year);
        $stmt2->execute();
        $stmt2->close();
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

或者,如果您不想在此过程中了解详细信息,那么这会更快更简单:

// yada,yada - get a conx
$email = $_POST['email'];

/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO table2 SELECT * FROM table1 WHERE email=?")) {
    /* bind parameters for markers */
    $stmt->bind_param("s", $email);

    /* execute query */
    $stmt->execute();

    /* the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function */
}

(来源:从http://php.net/manual/en/mysqli.prepare.php复制并修改的示例)