0

I have very strange problem with PHP which I am starting to learn .. I have created tables in MySQL database with some data, and now I want to show them in webpage.

This is my source where I have this problem:

<?php
    // Here I open connection
    $con = mysql_connect("localhost","root","aaaaaa");
    // set the mysql database
    $db = mysql_select_db("infs", $con);

    // I check the connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    else {
        // It always goes here
        echo "Connected to database!";
    }

    // I am testing very simple SQL query.. there should be no problem
    $result = mysql_query("SELECT * FROM cathegories", $con, $db);

    if (!$result) {
        // but it always dies
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $query;
        die($message);
    }

    mysql_close($con);
?>

What is wrong?

Thanks in advance!

7

3 Answers 3

1

You are mixing mysql and mysqli. Try something like:

<?php   
    $con= new mysqli("localhost","user","passwd","database");
    if ($con->connect_errno){
      echo "could not connect";
    }

    $select = "SELECT * FROM tablename";

    if($result = $con->query($select)){
        while($row = $result->fetch_object()){
            echo $row->rowname."<br>";
        }
    }
    else { echo 'no result'; }
    $con->close();  
?>
Sign up to request clarification or add additional context in comments.

Comments

1
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $connection);

change to

// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);

1 Comment

the main issue from you was you used $connection to connect while you never defined it but did define $con as connector whats the error you get now?
0

mysql_query only takes two parameters - the actual SQL and then the link identifier (I assume in your case that's stored in $con; therefore remove $db from the third parameter).

You don't even need the second $con parameter really.

Where's the actual logic to connect to the database initially? Just because mysqli_connect_errno() doesn't return an error it doesn't mean the connection actually exists and that $con is available in the current scope.

I'd var_dump($con) before the mysql query to make sure it's a valid connection.

1 Comment

I have tried to check connection with var_dump($con), and it prints: "resource(2) of type (mysql link) ". This should be right as I think..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.