shlocko Posted July 3, 2013 Share Posted July 3, 2013 I will paste the code below. Okay so I've benn trying to work with SQL in php connecting to a MySQL Database I have hosted on my own computer. I am trying to use an HTML form to get in info I need. But when I hit SUBMIT I don't get the output I was looking for. Any ideas why my code wont work? Also, I am sorry if this is the wrong section, I am new to the forum, if this is the wrong section, can someone please point me to where i need to go? Thanks! <html> <form action="index.php" method="post"> <input type="text" name="username"><br> <input type="text" name="password"><br> <input type="submit"> </form> </html> <?php $uname = $_POST[username]; $pword = $_POST[password]; $con=mysqli_connect('localhost', 'root2', '', 'first_db'); //Check conbnection if(mysqli_connect_errno()) { echo 'Failed to connect: ' . mysqli_connect_error(); } else{ $result = mysqli_query($con,"SELECT * FROM members WHERE username=$uname"); while($row = mysqli_fetch_array($result)) { echo $row['username']; echo $row['password']; echo $row['id']; } } Quote Link to comment Share on other sites More sharing options...
Psycho Posted July 3, 2013 Share Posted July 3, 2013 A lot of problems there. For one you are trying to output the results AFTER the closing HTML tag. You are also not checking for all errors or doing it incorrectly (not passing $con to mysqli_connect_errno() ). Plus, the username value is not within quotes inside the query. Give this a try <?php $output = ''; if(isset($_POST['username']) && isset($_POST['password'])) { $con = mysqli_connect('localhost', 'root2', '', 'first_db'); //Check connection if (mysqli_connect_errno($con)) { $output .= 'Failed to connect: ' . mysqli_connect_error(); } else { //Format values for SQL query $unameSQL = mysqli_real_escape_string(trim($_POST['username'])); //$pword = mysqli_real_escape_string(trim($_POST['password'])); //Create and execute query $query = "SELECT * FROM members WHERE username = '$unameSQL'"; $result = mysqli_query($con, $query); //Check if query passed if(!$result) { $output .= "Error runing query: {$query}<br>Error: " . mysqli_error($con); } //Check if there were results elseif(!mysqli_num_rows($result)) { $output .= "There were no matching records to username '{$uname}'"; } //Process results else { while($row = mysqli_fetch_assoc($result)) { $output .= "Username: {$row['username']}<br>\n"; $output .= "Password: {$row['password']}<br>\n"; $output .= "ID: {row['id']}<br><br>\n"; } } } } ?> <html> <?php echo $output; ?> <form action="index.php" method="post"> <input type="text" name="username"><br> <input type="text" name="password"><br> <input type="submit"> </form> </html> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.