[英]“AND $_SESSION['user_id'] = posted_by” not working
[英]MAX(user_id) not working
我想從表中獲取最后一個插入ID,我正在使用MAX(user_id)
,但它不起作用(列user_id
是一個auto_increment字段),這是我的代碼
class.php
<?php
class Chat extends Core
{
public function addUser($email) {
$this->query("INSERT INTO `users`(`username`) VALUES ('" . $this->db->real_escape_string($email) . "') ");
$q = "select MAX(user_id) from `users`";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
}
}
}
?>
當我運行此查詢時,我收到這樣的警告消息
警告:mysql_fetch_array():提供的參數不是有效的MySQL結果資源
這是我的core.php
<?php
class Core {
protected $db,$result;
private $rows;
public function __construct() {
$this->db=new mysqli('localhost','root','','site');
}
public function query($sql)
{
$this->result= $this->db->query($sql);
}
public function rows(){
for($x=1;$x<=$this->db->affected_rows;$x++)
{
$this->rows[]= $this->result->fetch_assoc();
}
return $this->rows;
}
}
?>
有誰能夠幫助我。 謝謝。
您是否要獲取最后插入的ID
然后使用
$last_user_id = $this->db->insert_id();
建議
更好地使用ci db函數
public function addUser($email) {
$userData = NULL;
$result = $this->db->insert('users', array('users' => $email));
if ($result == TRUE) {
$user_id = $this->db->insert_id();
$query = $this->db->get_where('users', array('user_id' => $user_id));
$userData = $query->row_array();
}
return $userData;
}
看起來您在下面使用mysqli
,所以這可以做您想要的事情:
public function addUser($email)
{
$this->query("INSERT INTO `users`(`username`) ...");
$userid = $this->db->insert_id;
// ... etc ...
}
因為mysqli::$insert_id
是基於會話的,所以避免了導致錯誤標識符傳遞的競爭條件。
另請參見: mysqli::$insert_id
請使用以下功能,它將滿足您的要求。
mysql_insert_id()
使用以下一個獲取最后的ID:
mysql_insert_id();
不建議使用AS Mysql函數
mysqli_insert_id()
PDO::lastInsertId()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.