0

I currently have a php file with html code in it. At the beginning of the body tag im including a dbcon.php which contains a db connection, a query and a fetch_result. I now want to use those results later in the html file but i cant get it to work.

Website-file looks like this:

<html>
<head>...</head>
<body>
<?php include("dbcon.php"); ?>
...
<some html stuff>
...
<? here i want to use the data from the query ?>
...
</body></html>

The dbcon.php simply contains the connection, the query and the fetch_results.

edit: dbcon:

<?php

$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query($con,"SELECT * FROM table");
$results = mysql_fetch_array($results_query);

?>

I cant access the data in the lower part of the html file.

szpar
  • 11
  • 3
  • 1
    Please post dbcon.php – Liftoff Nov 26 '13 at 10:43
  • What do you mean when you say "I cant access the data in the lower part of the html file"? – John V. Nov 26 '13 at 10:44
  • 2
    [Please, stop using mysql_* functions](http://stackoverflow.com/q/12859942/1238019) in new code, they are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Instead of, have a look on [prepared statements](http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html), and use [Mysqli](http://php.net/manual/en/book.mysqli.php) or [PDO](http://php.net/manual/en/book.pdo.php). – zessx Nov 26 '13 at 10:51
  • Note that you are using the short open tags in the lower part. This only works if it is enabled. [link](http://php.net/manual/en/language.basic-syntax.phptags.php) – Bram Verstraten Nov 26 '13 at 10:55

2 Answers2

0

Your code is "right", in that you don't need anything more to access your dbcon.php variables.

But you're mixing mysql_ and mysqli_ syntax :

  • mysql_query take as first parameter the query, not the connexion
  • mysqli_query take as first parameter the connexion, and the query as second one

You should use mysqli_ :

$con = mysqli_connect("localhost:8889","user","pw","db");
$result_query = mysqli_query($con, "SELECT * FROM table");
$results = mysqli_fetch_array($results_query);

Another version, object oriented :

$mysqli = new mysqli("localhost:8889", "user", "pw", "db");
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}
$results = array();
if ($result_query = $mysqli->query("SELECT * FROM table")) {
    $results = $result_query->fetch_array();
} 
zessx
  • 68,042
  • 28
  • 135
  • 158
0

don't use mysql_ function,it is depricated.
anyway you use wrong variable name. $results_query in mysql_fetch_array($results_query) so change it to $result_query and it might work.

<?php

$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query("SELECT * FROM table");
$results = mysql_fetch_array($result_query );

?>
DS9
  • 2,995
  • 4
  • 52
  • 102