Error fetching from DB, but not sure what's wrong

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 954 Views - Last Post: 09 February 2013 - 05:22 AM Rate Topic: -----

#16 Sapper187  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 08-February 13

Re: Error fetching from DB, but not sure what's wrong

Posted 09 February 2013 - 04:59 AM

Before I get too far into rewriting my code, I want to make sure I'm converting things from mysql to mysqli correctly.

// Old code
function protect($string) {
    return mysql_real_escape_string(strip_tags(addslashes($string)));
}

// New code, $db is in my connect function to connect to the database
function protect($string) {
    $string = $db->real_escape_string(strip_tags(addslashes($string));
}

// Or can I do this?
function protect($string) {
    return $db->real_escape_string(strip_tags(addslashes($string));
}


This function is used on both my register.php and login.php here:

// register.php
<?php
if(isset($_POST['register'])){
    $username = protect($_POST['username']);
    $password = protect($_POST['password']);
    $email = protect($_POST['email']);
    
// login.php
$username = protect($_POST['username']);
$password = protect($_POST['password']);        


Am I both using and calling that correctly?
Was This Post Helpful? 0
  • +
  • -

#17 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,259
  • Joined: 08-June 10

Re: Error fetching from DB, but not sure what's wrong

Posted 09 February 2013 - 05:22 AM

View PostSapper187, on 09 February 2013 - 12:59 PM, said:

Am I both using and calling that correctly?

no.

unlike Java​Script, you cannot access variables from a parent scope inside functions. so you would have to pass the variables as well (also called Dependency Injection). and variables inside functions cannot be accessed outside of it (except for references variables, but that’s a whole different approch). Using global variables is out of question.

View PostSapper187, on 09 February 2013 - 12:59 PM, said:

// New code, $db is in my connect function to connect to the database
function protect($string) {
    return $db->real_escape_string(strip_tags(addslashes($string));
}

first, addslashes() is absolutely counter-productive (essentially you preserve inserted slashes in your data, which you would have to remove later). if any, it would be
function protect($string, $db) {
    return $db->real_escape_string(strip_tags(stripslashes($string));
}


on the other-hand-side, Prepared Ptatements make SQL Injection impossible (and the use of real_escape_string() obsolete). if you run your user data through validation/sanitisation by filter functions, strip_tags() (and related) is applied by default.

This post has been edited by Dormilich: 09 February 2013 - 05:23 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2