2013-08-22 20 views
1

我想提醒用戶如果數據庫的查詢或更新是成功還是失敗..如何在php中查詢成功時提醒用戶?

adduser.php

<?php 
include('sqlconnection.php'); 

$firstname = $_POST['fname']; 
$lastname = $_POST['lname']; 
$middlename = $_POST['mname']; 
$password = $_POST['pword']; 
$username = $_POST['uname']; 
$gender = $_POST['gender']; 
$utype = $_POST['utype']; 

$query = "INSERT INTO user (firstname,lastname,middlename,gender) VALUES ('$firstname','$lastname','$middlename','$gender')"; 

mysql_query($query); 

$result = mysql_query("SELECT id FROM user WHERE firstname = '$firstname'"); 

$row = mysql_fetch_assoc($result); 

mysql_query("INSERT INTO accounts (u_id,username,password,utype) VALUES ('$row["id"]','$username',md5('$password'),$utype);") 
?> 

我怎麼會提醒用戶?或者我應該怎麼用給用戶彈出消息說它成功了?

+1

只是一個旁註,你的代碼容易受到SQL注入的影響,並且不推薦使用'mysql_ *'函數。您可能希望閱讀[如何防止SQL注入PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)和[爲什麼shouldn'我在PHP中使用mysql_ *函數?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。 – 2013-08-22 02:21:10

+0

@ user2062950 thanks..is最好使用mysqli_? – jmjassy27

+1

是的,但PDO也可以。有一個[MySQL PHP驅動程序概述](http://www.php.net/manual/en/mysql.php),它提供了有關它們的詳細信息。 – 2013-08-22 02:28:33

回答

0

指定一個變量來MYSQL_QUERY,例如:

$result = mysql_query("your query"); 

if($result){ 
$xxx = "query successful"; 
}else{ 
$xxx = "query failed"; 
} 

在HMTL:

<script> 
alert(<?php echo $xxx;?>); 
</script> 

這是一種方式,從這裏可以發揮做任何你想要


As side注意:從PHP 5.5.0開始,不推薦使用Mysql_ *擴展,並且將來會被刪除。相反,應該使用MySQLi或PDO_MySQL擴展。

一個有用的鏈接Why shouldn't I use mysql_* functions in PHP

0

mysql_query()返回false無效查詢。 mysql_num_rows()返回像select一樣的查詢返回的記錄數。 mysql_affected_rows()檢查受影響的行。

EG:

$result = mysql_query("your query"); 

if($result){ 
    //query successful but this doesn't mean it returned anything 
    //you can now use mysql_num_rows (for select query) to check if something is returned 
    if(mysql_num_rows($result) > 0){ 
    //some results were returned 
    } 

    //for insert, update or delete query you need to check affected rows like this 
    if(mysql_affected_rows() > 0){ 
    //some records were updated or deleted 
    } 
}else { 
    echo "There was a problem"; 
} 

旁註:MySQL_*擴展不贊成PHP 5.5.0的,並會在將來被移除。改爲使用MySQLiPDO

相關問題