--------------------------错误代码------------------- ----------
第65行致命错误:未被捕获的错误:在C:\ xampp \ htdocs \ aa \ index.php:65中的null上调用成员函数prepare()堆栈跟踪:#0 C:\ xampp \ htdocs \ aa \ index.php(102):heart(2,':: 1')#1 {main}在第65行的C:\ xampp \ htdocs \ aa \ index.php中抛出
--------------------------数据库连接------------------- ----------
<?php
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','heart');
// Establish database connection.
try
{
$con= new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,
DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
?>
------------------------------- index.php代码------------ -------------------
<?php
function heart($mediaId, $userId) { // Function called "heart". We pass 2
arguments, the media Id and our user Id
require_once ('connexion.php'); // Connection to database
$heart = '<div id="lineBlock">'; // See the CSS, we align the 2 div: heart
div and value
$select = $con->prepare('SELECT value FROM heart_votes WHERE media = ? AND
user_id = ?'); // We check the current heart value (0 or 1) for our user Id
$select->execute(array($mediaId, $userId));
$getVal = $select->fetch();
if (isset($getVal['value'])) { // If the value exists (if we have a record in the database table)
if ($getVal['value'] == true) $heart .= '<div id="heart'.$mediaId.'" class="oneLine heart_icon on" rel="'.$userId.'"></div>';
if ($getVal['value'] == false) $heart .= '<div id="heart'.$mediaId.'" class="oneLine heart_icon off" rel="'.$userId.'"></div>';
} else { // Else we create the ligne in the database
$insert = $con->prepare('INSERT INTO heart_votes (media, user_id, value) VALUES(:media, :user_id, :value)');
$success = $insert->execute(array(
'media' => $mediaId,
'user_id' => $userId,
'value' => false
));
$heart .= '<div id="heart'.$mediaId.'" class="oneLine heart_icon off" rel="'.$userId.'"></div>';
}
// Next to the heart we display the number of vote
$numVote = $con->prepare('SELECT value FROM heart_votes WHERE media = '.$mediaId.' AND value = 1');
$numVote->execute();
$numVote->setFetchMode(PDO::FETCH_OBJ);
$heart .= '<div class="oneLine num_vote" id="heart_num_vote'.$mediaId.'">'.$numVote->rowCount().'</div>';
$heart .= '</div>';
return $heart;
}
$userIP = $_SERVER['REMOTE_ADDR']; // Get User IP address
$userId = str_replace('.', '', $userIP); // Remove the . "dot" from the IP
address to have a unique integer
echo '<p>';
echo heart(1, $userId); // Media Id, user Id
echo '</p>';
echo '<p>';
echo heart(2, $userId);
echo '</p>';
?>`
`