Searching a DB for the existence of a string (php, mysql)
I've been learnging php/mysql for a short while and I got some basic stuff working that allowed me to make a chat server.
Can create the DB, post a message, retrieve new messages.
I've hit a brickwall now while trying to create a script to allow usernames to be created. There are not passwords involved in this. 3 steps involved in this i think.
- The user submits a username to the server along with there Unique ID and if the name doest exist, then I add the name and there uid to the DB and the name belongs to that uid and nobody else can take it and I echo 'Success' back to the client.
- If they submit a name thats already there in the DB, but the clients uid matchs the uid associated to the name in the DB, then i just echo back 'Success'. no need to add anything to the DB开发者_StackOverflow中文版.
- They submit a name and uid to the DB, the name is already taken and the uid associated with that name in the DB does not match with this clients uid so i echo back 'Fail' to the client.
This is what I've done so far in my script. I added in pseudo code for where I dont yet understand how to create the necessary logic.
<?php
// put_score.php
/** MySQL database name */
define('DB_NAME', 'db_Chat');
/** MySQL database username */
define('DB_USER', 'chat_App');
/** MySQL database password */
define('DB_PASSWORD', 'smile123');
/** MySQL hostname */
define('DB_HOST', $_ENV{DATABASE_SERVER});
$table = "ab_username";
// Initialization
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
if($_GET['secret'] != "some_secret") {
die('Nothing to see here...');
}
// Localize the GET variables
$udid = isset($_GET['udid']) ? $_GET['udid'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
// Protect against sql injections
$udid = mysql_real_escape_string($udid);
$name = mysql_real_escape_string($name);
if username exists in the DB
{
if the UID associated with that username in the database matchs the UID submited by the client the echo 'Success'
else echo 'Fail'
}
else // add name and UID to database echo 'Success'
{
// Insert the username
$retval = mysql_query("INSERT INTO $table(
udid,
name
) VALUES (
'$udid',
'$name'
)",$conn);
if($retval) {
echo "Success";
} else {
echo "Fail";
}
}
mysql_close($conn);
?>
If anybody could help me get the replace the pseudo code it would be very much appreciated.
Many Thanks, -Code
Can't test this currently, but this is pretty much what you need:
$udid_mismatch=false;
$name_found=false;
$result = mysql_query("SELECT udid FROM table WHERE name='$name'");
while( $row = mysql_fetch_assoc($result) ){
$name_found=true;
if($row['udid'] != $udid){
$udid_mismatch=true;
}
break;
}
if($name_found && $udid_mismatch ){
echo 'Fail';
} else if($name_found) {
echo 'Success';
} else {
//Insert the username
}
Be sure to replace "table" in the query with your correct table name.
精彩评论