Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

m7a7d

macrumors newbie
Original poster
Feb 27, 2010
23
0
I just posted another thread on the mail() function (resolved). However, now I'm faced with a mysqli_query() problem.

I'm getting "Unable to query MySQL server:" from the following code. I am totally stumped as to why it can't query successfully.

PHP:
<?php
  $first_name = $_POST['firstname'];
  $last_name = $_POST['lastname'];
  $when_it_happened = $_POST['whenithappened'];
  $how_long = $_POST['howlong'];
  $how_many = $_POST['howmany'];
  $alien_description = $_POST['aliendescription'];
  $what_they_did = $_POST['whattheydid'];
  $fang_spotted = $_POST['fangspotted'];
  $other = $_POST['other'];
  $email = $_POST['email'];
  
  $dbc = mysqli_connect('localhost', 'myUser', 'myPass', 'myDB');
  
  if(!dbc) {
    die('Unable to connect to MySQL server.' . mysqli_error());
  }
    
  $query = "INSERT INTO aliens_abduction (first_name, last_name, when_it_happened, " .
    "how_long, how_many, alien_description, what_they_did, fang_spotted, other, email) " . 
    "VALUES ('$first_name', '$last_name', '$when_it_happened', '$how_long', '$how_many', " .
    "'$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')";
    
  $result = mysqli_query($dbc, $query)
    or die('Unable to query MySQL server:' . mysqli_error());
  
  mysqli_close($dbc);
?>


:confused:
 
The if statement, you're missing the $ on dbc.

Another note, you're coding is very vulnerable to SQL-injection attack because you're not sanitizing the data you're getting from $_POST. Check out this PHP security starter document to get you understanding the vulnerabilities in your code and how to fix them.
 
angelwatt,

Thank you for your reply.

Ok, so I fixed the if(!$dbc) and the problem was in mysqli_connect(). I replaced 'localhost' with '127.0.0.1,' and it worked. Why will it accept '127.0.0.1' and not 'localhost' for a server name?

Thanks for the security link. I just started PHP today so I'm still a noob :rolleyes:

Thanks again!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.