How to prevent an SQL injection in PHP?

New to php and sql. Want to store a value in a session, how do I do that?

  • This is a check login info page, and I have it so it checks the login info and creates a session, but I can only add the variables from the login to the session...how do I add other info from the specific record to the session? I have this so far: <?php $host="localhost"; // Host name $username="username"; // Mysql username $password="password"; // Mysql password $db_name="db"; // Database name $tbl_name="tablename"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; $status=2; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE email='$myusername' and password='$mypassword' and status='$status'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ $row=mysql_fetch_array($result); $result['lname']=$row['lname']; $_SESSION['myusername']=$row['myuserna… header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> In this row "$result['lname']=$row['lname'];" I am trying to pull the users last name from the db but it doesnt work at all....any ideas??

  • Answer:

    Any page that makes use of session variables must call the session with the function 'session_start()' The first 2 lines in your script above should be <?php session_start(); Without this no session is started or resumed. All about PHP and sessions: http://php.net/session_register $result contains the result of your query. By defining $result again, your query results are lost. You can use $row['lname'] itself: It contains the value of 'lname' from your database. If you want it stored in the session define: $_SESSION['lname']=$row['lname']; In any other page you can use the $_SESSION variables: echo $_SESSION['lname']; Make sure the page resumes the session by calling the function session_start() .

trafficm... at Yahoo! Answers Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.