0

Everyone says printing data from a MySQL database is easy but so far I'm stumped. I am new to PHP, and am trying to print out an individuals data from a database. So for example Joe Bloggs has logged in, and then he can view what his hobbies are etc. So what I am trying to achieve is getting a user to log in and see THEIR info.

Basically, the user can log in, however I tried to set a up variable to store the SQL query and then print it out if the user logged in successfully, however I now get the following error message- that will no go away.

( ! ) SCREAM: Error suppression ignored for
( ! ) Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in    C:\wamp\www\myfiles\login.inc.php on line 32
Call Stack
#   Time    Memory  Function    Location
1   0.0015  365584  {main}( )   ..\index.php:0
2   1.0144  387472  include( 'C:\wamp\www\myfiles\login.inc.php' )  ..\index.php:6
3   1.0427  390752  mysql_fetch_array ( )   ..\login.inc.php:32

    

Like virtually all beginners I have made the mistake of creating a massive file that overcomplicates what am trying to code,(it is also very late a night and I'm tired hence why I might not be able to see any errors). However it is well commented

I would appreciate any comments and suggestions!!

// create variables username and password,if a user doesn't enter a UN and PW send error message
if (isset($_POST['username'])&& isset ($_POST['password'])){
    $username= $_POST['username'];
    $password= $_POST['password'];

    if (empty ($username)&&empty ($password)){
        echo 'supply username and password';
    }
// save  our MySQl queries as variables in order to reference them later on

    // for login
    $query = "SELECT * FROM `students` WHERE `username`='$username'AND `password`='$password'";
    // user login result
    $result= mysql_query($query);
    // display the courses that user is taking
    $user= "SELECT * FROM `students`";

// set conditions for login 
    if($result) {
    // if the data matches by rows send a message saying the user has logged in
        if(mysql_num_rows($result) > 0) {
            session_regenerate_id();
            $member = mysql_fetch_assoc($result);

            $_SESSION['SURNAME_NAME'] = $member['username'];
            $_SESSION['SESS_ID'] = $member['password'];
            session_write_close();
            //if logged on list course they are studying
            echo 'you are now logged in.<a href = "logout.inc.php">Log out</a>';
                while($row = mysql_fetch_array($user))
                {
                    echo $row['GivenName'],$row['username'], $row['password'],$row['Course1'],$row['Course2'], $row['Course2'];
                    echo "<br />";
                }
            exit();
        }else {
            // create boolean condition- if no match send error message
            $errflag = true;
            if($errflag) {
            session_write_close();
            echo 'invalid username/password combination';   
            exit();

            }
        }
    }else {
    // display errors
        echo mysql_errno() . ": " . mysql_error(); exit();

    }

}

?>
<form method="POST">
Username: <input type = "text" name="username"> Password: <input type ="password" name="password">
<input type="submit" value="Log in">
</form
seanbreeden
  • 6,104
  • 5
  • 36
  • 45
  • 4
    [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](http://j.mp/XqV7Lp). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. – Kermit Apr 03 '13 at 00:47
  • Variable $user contains string "select....". Mysql_fetch_array needs resource to be parameter. So try $tmp = mysql_query($user) and next while($row = mysql_fetch_array($tmp))... – Miroslav Stopka Apr 03 '13 at 00:53
  • If your users can have multiple courses, you might also consider storing that in a separate lookup table between your students table and a courses table. YOur lookup table would have the user id and the course id. – Revent Apr 03 '13 at 00:53

3 Answers3

3

Heres are some of basics step that may help you if your a beginner in using php and mysql depends on what connection you are suitable to use..

MYSQLI :

FIRST : SET UP CONFIGURATION FOR DATABASE USER,PASS,HOST,DBNAME

$conn = new mysqli('database_server','database_username','database_password','database_name');

SECOND : Create a Query(you may insert your query here)..

$result= $conn->query("SELECT SUM(Total_Steps) AS value_sum FROM users");

FINAL : SHOWN RECORDS USING MYSQL FUNCTIONS LIKE..

while($row = $result->fetch_assoc()){
    echo $row['dabatase_columnname'];
    echo $row['database_columnname'];
}

PDO :

Connect to Database db = new PDO("...");

Create a Query

$statement = $db->prepare("select id from some_table where name = :name");

Execute query with the bind paramater

$statement->execute(array(':name' => "Jimbo"));

Fetch all data return by query

$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator

MYSQL :

FIRST : SET UP CONFIGURATION FOR DATABASE USER,PASS,HOST,DBNAME

$conn = mysql_connect('database_server','database_username','database_password');
mysql_select_db($conn,'databasename')

SECOND : Create a Query(you may insert your query here)..

$result= mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users");

FINAL : SHOWN RECORDS USING MYSQL FUNCTIONS LIKE..

while($row = $result->mysql_fetch_array($result)){
    echo $row['dabatase_columnname'];
    echo $row['database_columnname'];
}
Jhonathan H.
  • 2,734
  • 1
  • 19
  • 28
0

the problem is you didn't do this:

 mysql_query($user);

just add before the mysql_fetch_array like:

$user_result = mysql_query($user);
while($row = mysql_fetch_array($user_result)){
     //...
}

But, yes, as another said, please use MySqli or PDO instead.

egig
  • 4,370
  • 5
  • 29
  • 50
0

As noted, avoid using mysql_* functions in new code. They are no longer maintained and are officially deprecated.

Here is an example of your code, using PDO, and prepared statements. You should probably only have to change connection information.

<?php
// Get your connection sorted.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
// Prepare a few statements for use later.
$stmtResult = $db->prepare("SELECT * FROM `students` WHERE `username`=?AND `password`=?");
$stmtUser = $db->prepare("SELECT * FROM `students`");

// create variables username and password,if a user doesn't enter a UN and PW send error message
if (isset($_POST['username'])&& isset ($_POST['password'])){
    $username= $_POST['username'];
    $password= $_POST['password'];

    if (empty ($username)&&empty ($password)){
        echo 'supply username and password';
    }

    // Use the try catch paradigm instead of if/else, because PDO will
    // throw an exception if things go sideways.
    try{
        // Execute the prepared statement, passing in the variables.
        $stmtResult->execute(array($username, $password));
        // Get the results in an array & then get the result count.
        $rows = $stmtResult->fetchAll(PDO::FETCH_ASSOC);
        $row_count = $stmt->rowCount()

        if($row_count > 0) {
            session_regenerate_id();
            $member = $rows[0];

            $_SESSION['SURNAME_NAME'] = $member['username'];
            $_SESSION['SESS_ID'] = $member['password'];
            session_write_close();
            //if logged on list course they are studying
            echo 'you are now logged in.<a href = "logout.inc.php">Log out</a>';
            $stmtUser->execute();

            // I moved this next call down to the loop because
            // there is no real reason to call it sooner than this
            while($row =  $stmtResult->fetchAll(PDO::FETCH_ASSOC))
            {
                echo $row['GivenName'],$row['username'], $row['password'],$row['Course1'],$row['Course2'], $row['Course2'];
                echo "<br />";
            }
            exit();
        }else {
            // create boolean condition- if no match send error message
            $errflag = true;
            if($errflag) {
            session_write_close();
            echo 'invalid username/password combination';   
            exit();

            }
        }
    }catch(PDOException $ex) {
        // This is what happens if something did go sideways.
        echo $ex->getCode() . ": " . $ex->getMessage(); 
        exit();
    }
}

?>
<form method="POST">
Username: <input type = "text" name="username"> Password: <input type ="password" name="password">
<input type="submit" value="Log in">
</form
Zoe
  • 27,060
  • 21
  • 118
  • 148
bubba
  • 3,839
  • 21
  • 25