Karma5
Karma5

Reputation: 273

Connect php with server

I am connecting to server with help of php for an android application. Name of Database in phpmyadmin is "student" , name of table is "data" and fields are "Name" and "EmpId" This is what I coded n php and getting the error on the "$output" part as undefined variable Here is the code:

<?php
$connection = connectionserver ();
function connectionserver (){

$con = mysql_connect("localhost", "root", "") or die ("connection not found");

if($con) 
echo "Connection Created" ,"<br>";


$database = mysql_select_db ("student1", $con);

if($database) echo "Database Connected" , "<br>";
return $con;

}

$result = mysql_query("select * from data");
while ($row = mysql_fetch_assoc($result))
{
   $output [] = $row;
}
    print json_encode($output);
    mysql_close($connection);


?>

Upvotes: 0

Views: 89

Answers (4)

user3209375
user3209375

Reputation: 21

$undefined_array[] = 'something' will not trigger an E_NOTICE error. However it is good practice to initialize the variable.

The error comes from the line with json_encode, most likely because your query didn't return any result, didnt get into the while loop, thus $output[] was never executed.

Upvotes: 1

Krish R
Krish R

Reputation: 22711

Try this,

        echo connectionserver();

        function connectionserver (){           
                $con = mysql_connect("localhost", "root", "") or die ("connection not found");                          

                $database = mysql_select_db ("student1", $con);                                     

                $result = mysql_query("select * from data") or die(mysql_error());
                $output = array();
                while ($row = mysql_fetch_assoc($result))
                {
                    $output[] = $row;
                }                   
                mysql_close($con);
            return  json_encode($output);           
        }

Upvotes: 0

Tasfin
Tasfin

Reputation: 32

You may try this:

<?php
$connection = connectionserver ();

function connectionserver (){

$con = @mysql_connect("localhost","root","");   
if(!$con) die("Can't connect!!");    

$var2 = @mysql_select_db("student1",$con);
if(!$var2)
    die("<br>"."can't select dataBase");

$result = mysql_query("select * from data");

while ($row = mysql_fetch_assoc($result))
{
   $output[] = $row;
}

print json_encode($output);

mysql_close($con);

}
?>

Upvotes: 0

gmlv
gmlv

Reputation: 368

declare $output as array before the while

  $output = array();

Upvotes: 2

Related Questions