Jump to content

Can't figure out the correct coding


BigAl75

Recommended Posts

Can someone help me with the coding for this? I can't figure out the correct way to code the follow:open table siteusersif (username = exists){get userid}else{add username (userid is set to auto increment)}I am trying to create a way for a user to easily add updates to his website. I figured using php & mysql would be about the easiest. The problem is, when ever you add the username to a new post, and try to add the post to the db, you get the error message because the username all ready exists.

Link to comment
Share on other sites

What I posted is just explaining what I want to do. It wasn't supposed to be the actual code, which is what I'm trying to figure out how to write.I've got an idea of what the code is suposed to look like, but I can't get it from my head to the keyboard.Al

Link to comment
Share on other sites

if(isset($_POST['add']))	{	include 'library/config.php';	include 'library/opendb.php';		$username = $_POST['username'];	$post = $_POST['post'];		$query = "INSERT INTO houndposts (username, post) VALUES ('$username', '$post')";	mysql_query($query) or die('Error, insert query failed');		include 'library/closedb.php';	echo "New Post Added";	}

This is what I have so far. After I got this to work, I realized that if the user has the same name when trying to make another post, it creates an error. What I want it to do is to check the username against the names listed in the new table houndusers (which I created after this). If it's all ready there, get the userid from that table, then add the userid and the post to the houndposts table.I think it should go something like this, but I can't get the coding correct:

if (username all ready exists){get userid from table houndusers}else{add username and get new userid}$query = "INSERT INTO houndposts (userid, post) VALUES ('$userid', '$post')";mysql_query($query) or die('Error, insert query failed');		include 'library/closedb.php';	echo "New Post Added";	}

It's the first part of this new code I'm having trouble with.I apologize if my questions aren't very clear. I've always had trouble forming my questions correctly, and normally do get "I'm not sure what you're asking" as my responses. I do try to ask better questions, but have difficulty in forming them correctly. Thanks for your patience and your help.Al

Link to comment
Share on other sites

well what you can do is open the file the username are kept in with fopen.put that into a stringthen take the string and break it into an array.break it again if the file has anything more than just user names.then run an if statement (if(x=0, x < $filesize, X++))then inside that compair username to the array you broke down... $username ==$array[$x]and if that's true, then you don't want that used again! Then display something like "Username is taken"

$file = fopen("list.txt", "r");$filesize = filesize("list.txt");$text = fread($file, $filesize);fclose($file);$explodedtext = explode("\n", $text);for($i = 0; $i < sizeof($explodedtext); $i ++){	$tempstring = explode('<2ndbreak>', $explodedtext[$i]);	if($tempstring[0] == $username)	{  $userFound = 1;	}}if($userFound != 1){	print "Can't use that username.<br /><br /><a href='javascript:history.back(1);'>Back</a>";	exit;}if($userFound == 1){$filename = "list.txt";$file = fopen("$filename", "a");$filesize = filesize("$filename");fwrite($file, "$username\n");fclose($file);}

this code has a 2nd break and some extra php because I made it for a login...with a 2nd break you could add password, date created, email, IP address...

Link to comment
Share on other sites

Here is a partial script, copied from a tutorial (about login using sessions, Dutch tutorial so no good here) but I think you'll get the idea.

$Query = mysql_query("SELECT * FROM users WHERE username = '$login'");    $Results = mysql_num_rows($Query);        if ($Results == '1') {

Basically what it does is search the database for a username. I think you'll make sure that on a logon system, each username is unique. So this little piece of code checks if a username exists in the database by counting the number of results in the searchquery. You can base your if/else code on that output.Getting the idea will look something like this (this is no actual script, just an explanation what you can do)

{$query = mysql_query("SELECT id FROM users WHERE username = '$login'");}ELSE{//add the user to the database in some way.}

or something similar to this.Note: I've only been doing this for a month now, but not a week passed without me googling for new pieces of code to adapt for my purposes. (or at least that's what my self-education comes down to.)The complete piece of code (in the Dutch tutorial, but still useful) is right here.Happy coding. :)PS:

I can't get it from my head to the keyboard.Al

Fix that. :) Finding out how to code only gets you halfway. Trial&Error (aka 'debugging') will take care of 'almost' everything else.
Link to comment
Share on other sites

  • 3 weeks later...

OK, this is what I have on the "post" page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Untitled Document</title></head><body><?phpif(isset($_POST['add']))	{	include 'library/config.php';	include 'library/opendb.php';		$username = $_POST['username'];	$post = $_POST['post'];		$result = mysql_query("SELECT username FROM houndusers") or die(mysql_error());		if(!$username)  { 	 $query = "INSERT INTO houndusers (username) VALUES ('$username')";  }  $query1 = "INSERT INTO houndposts (post) VALUES ('$post')";    mysql_query($query1) or die('Error, insert query failed');    include 'library/closedb.php';	echo "New Post Added";	}else{?><form method="post" enctype="multipart/form-data">  <table align="center" cellspacing="15">    <tr>       <td align="left" valign="top">Username: <input name="username" type="text" id="username"></td>    </tr>    <tr valign="top">       <td align="left">Post:<br /> <br /> <textarea name="post" type="textarea" cols="75" rows="10" id="post"></textarea></td>    </tr>   <tr align="center">       <td valign="top"> <input name="add" type="submit" id="add" value="Add New Post">           <input name="Reset" type="reset" value="Reset">      </td>    </tr>  </table></form><?php}?></body></html>

And this is what I have on my "display" page:

<?phpinclude 'library/config.php';include 'library/opendb.php';/*$query  = "SELECT userid, post FROM houndposts";*/$query = "SELECT houndusers.username, houndpost.post FROM houndusers, houndposts WHERE houndusers.userid = houndposts.userid";/*$query2 = "SELECT userid, username FROM houndusers INNER JOIN houndposts WHERE houndusers.userid = houndposts.userid";SELECT Employees.Name, Orders.ProductFROM Employees, OrdersWHERE Employees.Employee_ID=Orders.Employee_ID*/$result = mysql_query($query);while(list($username,$post)= mysql_fetch_row($result)){?> <table>  <thead>    <tr>    <th>   	 Posted by :<br /><br /><? echo "$username "; ?>    </th> 	 </tr>	</thead> 	 <tr>    <td>    	 <? echo "$post"; ?>    </td> 	 </tr></table><?}include 'library/closedb.php';?>

The only problem I'm having now is that it's not adding the user name to the 'houndusers' database. Because of this, I don't know if '$query2' is working or not.One other small thing, how would I get the posts to show descending? I know it's DESC, but not sure where to put that.Thanks for the help.Al

Link to comment
Share on other sites

You need this for your post page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Untitled Document</title></head><body><?phpif(isset($_POST['add'])){  include 'library/config.php';  include 'library/opendb.php';  $username = $_POST['username'];  $post = $_POST['post'];  $result = mysql_query("SELECT userid FROM houndusers WHERE username='" . mysql_escape_string($username) . "'") or die(mysql_error());  if(mysql_num_rows($result) == 0)  {    mysql_query("INSERT INTO houndusers (username) VALUES ('$username')");    $userid = mysql_insert_id();  }  else  {    $row = mysql_fetch_assoc($result);    $userid = $row['userid'];  }  mysql_query("INSERT INTO houndposts (post, userid) VALUES ('" . mysql_escape_string($post) . "', '{$userid}')") or die('Error, insert query failed');  include 'library/closedb.php';  echo "New Post Added";}else{?><form method="post" enctype="multipart/form-data"> <table align="center" cellspacing="15">   <tr>     <td align="left" valign="top">Username: <input name="username" type="text" id="username"></td>   </tr>   <tr valign="top">     <td align="left">Post:<br /> <br /> <textarea name="post" type="textarea" cols="75" rows="10" id="post"></textarea></td>   </tr>  <tr align="center">     <td valign="top"> <input name="add" type="submit" id="add" value="Add New Post">         <input name="Reset" type="reset" value="Reset">     </td>   </tr> </table></form><?php}?></body></html>

Look at the differences between that one and yours, you can look on php.net for help about the functions used or ask about them here.To order a result set, you need an 'ORDER BY' clause, where you tell it what to order on. If you want to order by user id, you say 'ORDER BY userid'. If you want to order by username, it's 'ORDER BY username'. You can put ASC or DESC after that. So something like 'ORDER BY username DESC'. ORDER BY goes at the end of your SQL statement.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...