检查SQL数据库是否存在值,如果存在,则继续php

时间:2018-08-13 13:33:28

标签: php

我对php和SQL都是新手。有一个简单的留言簿。只需要允许来自数据库帖子注释的用户名。我尝试了Check SQL database if value exists and then return value if it does,然后将其修复为PDO,但仍然无法正常工作。请帮我;)

<?php
/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'username';

/*** mysql password ***/
$password = 'password';

$dbname = 'dbname';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

if($_POST['name']) {
    $name       = $_POST['name'];
    $message    = $_POST['message'];
    /*** set all errors to execptions ***/
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "INSERT INTO shoutbox (date_time, name, message)
            VALUES (NOW(), :name, :message)";
    /*** prepare the statement ***/
    $stmt = $dbh->prepare($sql);

    /*** bind the params ***/
    $stmt->bindParam(':name', $name, PDO::PARAM_STR);
    $stmt->bindParam(':message', $message, PDO::PARAM_STR);
  $result = $dbh->query("SELECT username FROM clients WHERE 'Username' = '$name'");
  $row_count = $result->rowCount();  
if ($result && $row_count >0){ 
    /*** run the sql statement ***/
    if ($stmt->execute()) {
        populate_shoutbox();
    }
 } 
} 
}
catch(PDOException $e) {
    echo $e->getMessage();
}

if($_POST['refresh']) {
    populate_shoutbox();
}



function populate_shoutbox() {
    global $dbh;
    $sql = "select * from shoutbox order by date_time desc limit 10";
    echo '<ul>';
    foreach ($dbh->query($sql) as $row) {
        echo '<li>';
        /*** echo '<span class="date">'.date("d.m.Y H:i", strtotime($row['date_time'])).'</span>'; ***/
        echo '<span> <b> Ник: </b>';
        echo '<span class="name">'.$row['name'].'</span>';
        echo '<span> <b> Сообщение: </b>';
        echo '<span class="message">'.$row['message'].'</span>';
        echo '</li>';
    }
    echo '</ul>';
}
?>

0 个答案:

没有答案