开发者

PHP and MySQL SELECT problem

Trying to check if a name is already stored in the database from the login user. The name is a set of dynamic arrays entered by the user threw a set of dynamic form fields added by the user. Can some show me how to check and see if the name is already entered by the login user? I know my code can't be right. Thanks!

MySQL code.

SELECT * 
FROM names 
WHERE name = '" . $_POST['name'] . "' 
AND userID = '$userID'

Here is the MySQL table.

CREATE TABLE names (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(255) NOT NULL,
meaning VARC开发者_运维百科HAR(255) NOT NULL,
PRIMARY KEY (id)
);


If $_POST['name'] is actually an array of strings, as you say, then try this PHP:

$namesString = '';
foreach ($i=0; $i < count($_POST['name']) $i++)
{
    $namesString .= "'" . mysql_real_escape_string($_POST['name'][$i]) . "'";
    if(isset($_POST['name'][$i + 1]) $nameString .= ', ';
}

With this query:

 SELECT * FROM `names` 
 WHERE `name` IN ( $namesString )
    AND `userID` = '$userID'

The query will return all the rows in which the name is the same as string in $_POST['name'].


First of all, if the userID field is unique, you should add a unique index on it in your table.

Also, watch out for SQL injection attacks!

Using something like this is much more secure:

$sqlQuery = sprintf('SELECT COUNT(id) AS "found" FROM names WHERE userID = "%s"', mysql_real_escape_string($_POST['name'], $conn));

This SQL query will return 1 row with 1 field (named found) which will return you the number of matched rows (0 if none). This is perfect if you only want to check if the userID exists (you don't need to fetch all data for this).

As for the dynamic array, you will have to post more information and I'll update my answer.

Meanwhile here are some usefull PHP functions that can help you do what you want:

For MySQL queries:

  • mysql_connect
  • mysql_real_escape_string
  • mysql_query
  • mysql_fetch_assoc

For your list of users:

  • explode
  • implode


Stated as you say, I'm quite sure the code does exactly what you are asking for. The SELECT should return the records that respond both to the name sent and the current user ID.

If you need some php code, here it is (should be refined):

$result = mysql_query('YOUR SELECT HERE'); 
if (!$result) {
   die('ERROR MESSAGE');
} else {
   $row = mysql_fetch_assoc($result)); 
   // $row is an associative array whose keys are the columns of your select.
}

Remember to escape the $_POST.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜