2017-01-27 19 views
0

所以基本上我得到這個代碼就在這裏:PHP(如果記錄不existant。)

<?php 
include_once 'dbconfig2.php'; 
$con = new DB_con(); 
$table = "users"; 
if(isset($_GET['profile_id'])) 
{ 
$sql=mysql_query("SELECT * FROM users WHERE user_id=".$_GET['profile_id']); 
$result=mysql_fetch_array($sql); 
} 
?> 

我無能,我將如何使它所以如果user_id是不是在記錄存在,他們不能查看他們的個人資料,但它導致他們另一個消息或一段代碼。

+1

somethjing像'如果(mysql_num_rows($ resullt)<1){死( '無效的用戶');}' 另外,你真的不應該使用PHP的MySQL功能。轉換爲MySQLI <注意最後的字母......非常簡單,並增加了腳本的安全性。還有其他選項,比如PDO –

+0

2005調用,他們希望他們的數據庫API回來! http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – miken32

+0

你應該使用準備的參數化語句,以避免sql注入。 – rescobar

回答

0

如果user_id不存在,結果中將不會有任何行。當您嘗試使用mysql_fetch_array()讀取一行時,它將返回FALSE。因此,你可以簡單地測試$result

if (!$result) { 
    die("Invalid profile ID"); 
} 
0

嘗試使用使用mysqli的預處理語句,以避免SQL注入。

舉例來說:

$mysqli = new mysqli("localhost", "root", "root", "test"); 
if ($mysqli->connect_errno) { 
    echo "connect_error". $mysqli->connect_error; 
} 
$id = $_GET['profile_id']; 
$result = $mysqli->prepare('SELECT name FROM users WHERE user_id = ?'); 
$result->bind_param("i", $id); 
$result->execute(); 
$result->bind_result($col1); 
$result->fetch(); 
$is_valid_profile = (!$col1) ? 'Invalid profile' : 'Valid profile'; 
echo $is_valid_profile; 
$result->close(); 

http://php.net/manual/en/mysqli.prepare.php