Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I made my first script of MySQLi. I have just learnt it from 3rd party website. So, I am not sure i am using functions which are not deprecated or outdated. I should start to practice good scripts to access databases. So, I have posted here. Any mistake you see, please point it out.

<?php

include "functions.php";

$a = checkLogin();

if($a==1) {
    $id = $_COOKIE['id'];

    include "databaseConnector.php";

    $query = $mysqli->query("SELECT * FROM users WHERE id = '$id'") or die($mysqli->error.__LINE__);

    if($query->num_rows > 0) {
        while($row = $query->fetch_assoc()) {
?>
            <?php echo stripslashes($row['firstname'])." ".stripslashes($row['lastname']); ?>   
<?php
        }
    }
    else {
        return false;   
    }
}
else {
    redirectIndex();
}

?>
share|improve this question
    
("SELECT * FROM users WHERE id = '$id'") - read about SQL injection! –  Peter Kiss Mar 7 '13 at 19:57
add comment

2 Answers

mysqli is somewhat outdated, you should see PDO that is much better both with security and database support (12 drivers vs. 1).

You can see here details of mysqli vs. PDO: http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/

share|improve this answer
add comment
<?php

include "functions.php";

$a = checkLogin();

if ($a == 1) {
    $id = $_COOKIE['id'];

    // include "databaseConnector.php";
    // --------------------------------------------------------------------------------------------------
        try {
            $handle = new PDO("mysql:host=$host_addr;dbname=$database", $username, $password);
            $handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    // --------------------------------------------------------------------------------------------------

    // UNBOUND PARAMETERS VERSION
        $query = "SELECT * FROM users WHERE id = '$id'";
        $statement = $handle->prepare($query);
        $statement->execute();

    // BOUND PARAMETERS VERSION
        $query = "SELECT * FROM users WHERE id = :id";
        $statement = $handle->prepare($query);
        $params = array(":id" => $id);
        $statement->execute($params);

    $row_count = $statement->rowCount();
    $result    = $statement->fetchAll(PDO::FETCH_ASSOC);

    if($row_count > 0) {
        foreach ($result as $row => $col) {
            echo $col['firstname']." ".$col['lastname']; 
        }
    } else {
        return false;   
    }
} else {
    redirectIndex();
}

?>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.