sorry for bad english in advance I am a new learner plz help me to optimize this code i have 2 table 1 questions and second authors whenever someone wants to post a question firstly i check whether the author name and email id matches in authors table if yes then i simply ad question in questions table with author id else i save authors name and email in db and then i obtain id of author to put question with author id in question table. <?PHP ob_start(); $host='localhost'; $username='root'; $password=''; $db_name='iqa'; $tbl_name_1='authors'; $tbl_name_2='questions'; mysql_connect($host,$username,$password) or die('Cannot Connect'); mysql_select_db($db_name) or die('Cannot Find'); $name=$_POST['name']; $email=$_POST['email']; $question=$_POST['question']; $name=trim($name); $email=trim($email); $question=trim($question); $name=stripslashes($name); $email=stripslashes($email); $question=stripslashes($question); $name=mysql_real_escape_string($name); $email=mysql_real_escape_string($email); $question=mysql_real_escape_string($question); $sql="SELECT * FROM $tbl_name_1 WHERE aname='$name' and aemail='$email'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if(!$count==1){ $sql="INSERT INTO $tbl_name_1 SET aname='$name', aemail='$email'"; $result=@mysql_query($sql); if(!$result) exit("Error in inserting Question"); $sql="SELECT id FROM $tbl_name_1 WHERE aname='$name'"; $result=mysql_query($sql); $row=mysql_fetch_array($result); $id=$row['id']; $sql="INSERT INTO $tbl_name_2 SET question='$question', authorid='$id', datetime=CURDATE()"; $result=mysql_query($sql); } else{ $sql="SELECT id FROM $tbl_name_1 WHERE aname='$name' and aemail='$email'"; $result=mysql_query($sql); $row=mysql_fetch_array($result); $id=$row['id']; $sql="INSERT INTO $tbl_name_2 SET question='$question', authorid='$id', datetime=CURDATE()"; $result=mysql_query($sql); } echo $id; ob_end_flush(); ?> PHP:
My suggestion here is simple. make a different table for user infos and user infos.. first: see if the username matches the database and if yes proceed.. second: match the id of the username and the id of user input so that you can call it together. don't confuse yourself. hope this would help..
i dont understand what u say? any more sugestion plzzzzzz mysql_real i used for the prevent of /n, /t etc
my advice is, use some php frameworks.. ie. codeigniter if your are a starter, why not put this under a class.. the functions are redundant.
You dont need to use stripslashes its like escaping and unescaping again, just use mysql_real_escape_string however if you have magic quotes its a different story