unable to get a function to write a global variable to me DB

Hi
I hope someone can help,
I have written the following function to write records to a mysql database. and it writes all the fields except custid.

I have attached the page that calls the function, but can’t work out the problem, please help and let me know what I am doing wrong… :frowning:

[php]function insert_address($address) {
global $db;

$custid = $_SESSION['custid'];

$sql = "INSERT INTO address ";
$sql .= "(custid, houseno, street_1, street_2, town, county, postcode, country) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $address['custid']) . "',";
$sql .= "'" . db_escape($db, $address['houseno']) . "',";
$sql .= "'" . db_escape($db, $address['street_1']) . "',";
$sql .= "'" . db_escape($db, $address['street_2']) . "',";
$sql .= "'" . db_escape($db, $address['town']) . "',";
$sql .= "'" . db_escape($db, $address['county']) . "',";
$sql .= "'" . db_escape($db, $address['postcode']) . "',";
$sql .= "'" . db_escape($db, $address['country']) . "'";
$sql .= ")";
$result = mysqli_query($db, $sql);


// For INSERT statements, $result is true/false

if($result) {
  return true;
} else {
  // INSERT failed
  echo mysqli_error($db);
  db_disconnect($db);
  exit;
}

}
[/php]


address .txt (2.74 KB)

First some observations you should be using prepared statements, I have no idea what db_escape() is (I’m guessing some self-made escape function that is useless if you use prepared statements) and I’m also guessing you don’t have error reporting turned on. I would suggest using PDO instead of mysqli for in my opinion it’s easier to implement and you are NOT tied down to MySQL database.

With that said I’m guessing custid is either not being passed in (even though it supposedly passed in with sessions and that’s why error reporting is nice to have on locally :wink: ) or you actually want the mysql database to auto increment custid, so that probably means your database table is not set up properly.

One last thing, stop using global variables for that is a bad habit to get into and makes debugging harder (case in point your particular problem).

If you insist on using a function for doing writing and/or reading to a database table(s) then pass the database connection and variable(s) into the function, for example:

[php]function insert_address(array $address, $custId = \NULL, $db = \NULL) {
/* You code goes here */
} [/php]

That’s my input and I’m sure others here have theirs as well. HTH John

P.S. To prove that I practice what I preach here’s me passing an array to my database tables via a method (another term for function).
[php]if (isset($submit) && $submit === ‘register’) {

$data['username'] = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$data['password'] = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$data['verify_password'] = filter_input(INPUT_POST, 'verify_password', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$data['full_name'] = filter_input(INPUT_POST, 'full_name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$data['email'] = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$data['verify_email'] = filter_input(INPUT_POST, 'verify_email', FILTER_SANITIZE_EMAIL);
$data['private'] = filter_input(INPUT_POST, 'private', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (empty($data['private'])) {
    $data['private'] =  'no';
}

$validate = new FormValidation($data); // Pass the array to a validation class:

if ($validate->result) {
    /* All the data has validated proceed to saving and sending email verification */
    $sendEmail = new FormVerification();
    $result = $sendEmail->sendEmailVerification($data); // Passing an array to a class:
    if ($result) {
        $data['security_level'] = 'public';
        $data['confirmation_code'] = $sendEmail->confirmationNumber;
        $finalResult = $users->create($data); // Pass the same array to another class (Users class I believe):

        if ($finalResult) {
            header('Location: notice.php');
            exit();
        }
    }
} else {

    $invalid = TRUE; // Invalid Data being sent to Form - Have user re-enter:
}

}[/php]

My database connection gets passed into the class a different way, but it’s still not done by a global variable.

Thanks Strider64 for the response.
the db_escape function is

<?php require_once('db_credentials.php'); function db_connect() { $connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME); confirm_db_connect(); return $connection; } function db_disconnect($connection) { if(isset($connection)) { mysqli_close($connection); } } function db_escape($connection, $string) { return mysqli_real_escape_string($connection, $string); } function confirm_db_connect() { if(mysqli_connect_errno()) { $msg = "Database connection failed: "; $msg .= mysqli_connect_error(); $msg .= " (" . mysqli_connect_errno() . ")"; exit($msg); } } function confirm_result_set($result_set) { if (!$result_set) { exit("Database query failed."); } } ?>

I take your point about using global variables, and just put it in to try and force the value to be passed, have removed them now but still get the same result,
I am using session ID to pass the required variables while moving around.

<?php // Performs all actions necessary to log in an customer function log_in_customer($customer) { // Renerating the ID protects the customer from session fixation. session_regenerate_id(); $_SESSION['custid'] = $customer['custid']; $_SESSION['last_login'] = time(); $_SESSION['username'] = $customer['username']; return true; } // Performs all actions necessary to log out an customer function log_out_customer() { unset($_SESSION['custid']); unset($_SESSION['last_login']); unset($_SESSION['username']); // session_destroy(); // optional: destroys the whole session return true; } // is_logged_in() contains all the logic for determining if a // request should be considered a "logged in" request or not. // It is the core of require_login() but it can also be called // on its own in other contexts (e.g. display one link if a customer // is logged in and display another link if they are not) function user_is_logged_in() { // Having a cust_id in the session serves a dual-purpose: // - Its presence indicates the customer is logged in. // - Its value tells which customer for looking up their record. return isset($_SESSION['custid']); } // Call require_login() at the top of any page which needs to // require a valid login before granting acccess to the page. function require_user_login() { if(!user_is_logged_in()) { redirect_to(url_for('/login.php')); } else { // Do nothing, let the rest of the page proceed } } ?>

// Performs all actions necessary to log out an customer
function log_out_customer() {
unset($_SESSION[‘custid’]);
unset($_SESSION[‘last_login’]);
unset($_SESSION[‘username’]);
// session_destroy(); // optional: destroys the whole session
return true;
}

I have taken screen grabs of the entry form and DB table to show input and result.

David


I don’t see anywhere you are passing $customer to the function to set sessions.

I suggest you forget all about all those functions and write a script step by step and get it working. Then you can start putting code in functions as needed.

I would also highly recommend you start using PDO with prepared statements or at least learn how to use Mysqli properly (Which is a lot more work) https://phpdelusions.net/pdo

Hi all
issue is now fixed.

instead of $address [‘custid’] = $_POST[‘custid’] ?? ‘’; in the PHP form used $address [‘custid’] = $_SESSION[‘custid’] ?? ‘’;

Just because the code “works” does not mean it’s correct. For one thing, you never output internal system errors to the user. That information is only good to hackers. What is the user supposed to do with the system error message?

Sponsor our Newsletter | Privacy Policy | Terms of Service