Jump to content

Inserting Records Into Mysql Using Php


ApocalypeX
 Share

Recommended Posts

Using the "PHP Simple HTML DOM Parser" - PHP Simple HTML DOM ParserI'm learning PHP and I have the information collected from the webpage I now need to insert to mySQL database table to add in the results.Now when I write this:

<?phpinclude('simple_html_dom.php');$i=1;while($i<=3){$urlnumber = $i;$urling = "http://www.bungie.net/account/profile.aspx?uid=" . $urlnumber;$html = file_get_html($urling);foreach($html->find('span#ctl00_mainContent_header_lb lUsername') as $element)$con = mysql_connect("localhost","peter","a bc123");if (!$con){die('Could not connect: ' . mysql_error());}mysql_select_db("my_db", $con);mysql_query("INSERT INTO user_details (username)VALUES ($element->innerhtml)");mysql_close($con);$i++;}?>

No problems with the page just it doesnt add the record to my database. but if I change

mysql_query("INSERT INTO user_details (username)VALUES ('userone')");

It will add the record in.

Edited by ApocalypeX
Link to comment
Share on other sites

You need to figure out exactly what you're telling the server to do, and you should also be checking for error messages. After you make your query, print it out to make sure you're telling the server what you think you are.

$sql = "INSERT INTO user_details (username) VALUES ($element->innerhtml)";echo $sql;

Does the query look correct? You can copy and paste the query into phpMyAdmin and run it there, does it run there? You can add error checking to your PHP script also:

mysql_query($sql) or exit(mysql_error());

For one thing, when you're using objects or arrays inside strings it's best to use brackets to make sure PHP knows what you're trying to do:

$sql = "INSERT INTO user_details (username) VALUES ({$element->innerhtml})";echo $sql;

If you did all of that and checked for errors you should see that you are missing single quotes around the value. Note when you manually typed the username you wrote VALUES ('username'), not VALUES (username). If you print that query out you'll see that you're missing quotes. You'll also want to escape the data you're inserting to protect against SQL injection attacks.I could have just said you're missing quotes, but the point is that there is a lot you can do to get more information about the problem instead of just guessing or looking at it.

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
 Share

×
×
  • Create New...