PHP not displaying MYSQL result - php

I created a script on a windows platform which connects to the mysql database and returns the results of a table. A very basic script which I wrote to simply test my connection worked. The script works fine on my windows machine but not on my new mac. On the mac it simply does not display any records at all.
I know that the database connection has been established because there is no error but I can not see why the result set is not being displayed on screen, as I said it worked fine on my windows machine.
The Mac has mysql (with data) and apache running for php.
Please could someone help as I have no idea what to do now?
Script below:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'test';
mysql_select_db($dbname);
mysql_select_db("test", $conn);
$result = mysql_query("SELECT * FROM new_table");
while($row = mysql_fetch_array($result))
{
echo $row['test1'] . " " . $row['test2'] . " " . $row['test3'];
echo "<br />";
}
mysql_close($con);

There are various things you could do to debug this.
Show all PHP errors.
ini_set('display_errors','On');
ini_set('error_reporting',E_ALL);
Catch all possible MySQL errors, not only the ones concerning whether you connected successfully.
mysql_select_db("test", $conn) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM new_table") or die(mysql_error());
Side note: There's no reason to select which database you wish to use twice.

Its very difficult to see what is wrong ... so add some basic error checking, like changing this
$result = mysql_query("SELECT * FROM new_table");
to
$result = mysql_query("SELECT * FROM new_table") or die(mysql_error());
This will show you the error you are getting from your query (if there is one) .. you ill see in the documentation for mysql_query that it returns a boolean if there was an error
Also note that you have a mistake in the variable name for closing the MySQL Connection :
mysql_close($con);
should be
mysql_close($conn);

Check to see if the SELECT query was successful or not before fetching the rows.
<?php
$result = mysql_query("SELECT * FROM new_table");
if(!$result)
die('SQL query failed: ' . mysql_error());

The only thing i can think of is that Mac file system is case sensitive while windows isn't so it might be that you mispelled the name of the table. In any cas you should do
$result = mysql_query("SELECT * FROM new_table") or die("error:".mysql_error());
to view the error

I think you should use the improved PHP mysql driver
try
{
$db = new mysqli("localhost","root","root","test");
if ($db->connect_errno) {
throw new Exception($db->connect_error);
}
if ($result = $db->query("SELECT * FROM new_table")) {
printf("Select returned %d rows.\n", $result->num_rows);
while($row = $result->fetchAssoc())
{
echo $row['test1'] . " " . $row['test2'] . " " . $row['test3'];
echo "<br />";
}
/* free result set */
$result->close();
}
$db->close();
}
catch(Exception $e)
{
printf("Database Error: %s\n", $e->getMessage());
exit();
}

Related

Oracle + PHP : Display results in HTML Table

I'm having a little trouble tinkering with PHP and Oracle using OCI8 to connect. I've confirmed that i'm able to connect, but keep getting the below error:
PHP Fatal error: Call to a member function query() on resource ... on line 17.
Here's the code I have currently
<?php
$DB = '//DBGOESHERE:PORT/SIDHERE';
$DB_USER = '****';
$DB_PASS = '****';
$conn = oci_connect($DB_USER, $DB_PASS, $DB);
//check for errors
if (!$conn)
{
$e = oci_error();
print htmlentities($e['message']);
exit;
}
$sql = "select display_name, last_export_file, last_export_date from schema.ms_export where last_export_date > sysdate -1 order by last_export_date desc";
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (oci_fetch($stid)) {
echo oci_result($stid, 'display_name') . " | ";
echo oci_result($stid, 'last_export_file') . " | ";
echo oci_result($stid, 'last_export_date') . "<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Any help would be greatly appreciated! Technically I'm trying to get it to output into a pretty HTML table, but starting with cheap and dirty line breaks.
Thank you!
Ends up the above was correct and I hadn't synced the most recent version of the php file. Sorry for the trouble!

Connect to my database with PHP

I want to connect my HTML page to my database but I”m not getting it not sure why. What’s wrong with the code?
<?php
$con = mysqli_connect("localhost","root","","sibd02");
$query = sprintf("SELECT*FROM fornecedor ",
$result = mysql_query($query);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
There are lots of issues with your code. Here is my cleaned up version of your code which should work:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost", "root", "sibd02") or die(mysqli_connect_errno());
// Set the query.
$query = "SELECT * FROM fornecedor";
// Run the query.
$result = mysqli_query($con, $query) or die(mysqli_connect_errno());
// Print the result for initial testing.
echo '<pre>';
print_r($result);
echo '</pre>';
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
So let’s look at your original code with notes below on each issue:
$con = mysqli_connect("localhost","root","","sibd02");
$query = sprintf("SELECT*FROM fornecedor ",
$result = mysql_query($query);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
First this line $query = sprintf("SELECT*FROM fornecedor ", is incorrect syntax in PHP. And the sprintf is not needed.
Then your MySQL query would fail because it has it’s own syntax error: SELECT*FROM fornecedor That SELECT*FROM should have spaces like this SELECT * FROM.
Then you are using mysqli_connect for the connection but then using mysql_query for the query. Those are two 100% different functions in different classes. Mixing them like this will never work.
Mixing MySQL and MySQLi won't work. You can simply do this:
<?php
/* ESTABLISH CONNECTION */
$con=mysqli_connect("localhost","root","","sibd02");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$query = "SELECT * FROM fornecedor";
$result = mysqli_query($con,$query); /* EXECUTE QUERY */
/* IF YOU WANT TO PRINT THE RESULTS, HERE IS AN EXAMPLE: */
while($row=mysqli_fetch_array($result)){
echo $row['column']." ".$row['column2']." ".$row['column3']; /* JUST REPLACE THE NECESSARY COLUMN NAME */
} /* END OF WHILE LOOP */
mysqli_close($con);
?>

PHP: connected to database, but mysql_query fails

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!
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();
?>
// 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);
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.

how to Get the list of sites (domains) from MySQL database using PHP?

so I am new in StackOverflow :), I have a problem to answer a question in php5,
This is the question :
Create a PHP 5.4 script to check availability of many Sites (via Echo Protocol):
* Get the list of sites (domains) from MySQL database.
so I write this script and I want if it's the good answer :
<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
try something like this
$con = mysqli_connect(‘hostname’, ‘username’, ‘password’, ‘database’);
$result = mysqli_query($con , "select column_name from table_name");
while($data = mysqli_fetch_array($result))
{
echo $data['column_name'];
}
this will tell you the databases that have rights to be connected to
mysql_connect('localhost') or die ("Connect error");
$res = mysql_query("SHOW DATABASES");
while ($row = mysql_fetch_row($res)) {
echo $row[0], '<br/>';
}
You need to select a database before you use mysql_query.
$connection = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');
//Write code to Check the connection
mysql_select_db('database_name', $connection);
//Write code to query
But as Robin mentioned in the comment, mysql* apis are deprecated. Use Mysqli or Pdo_Mysql. details here: http://in3.php.net/mysql_select_db

Pass a PHP variable to a MySQL query

What is wrong with this code? I get an empty array. I am passing a PHP variable to the query, but it doesn’t work; when I give a hardcoded value the query returns a result.
echo $sub1 = $examSubject[$i];
$subType = $examType[$i];
$query = $this->db->query("select dSubject_id from tbl_subject_details where dSubjectCode='$sub1'");
print_r($query->result_array());
Look up “SQL injection”.
I’m not familiar with $this->db->query; what database driver are you using? The syntax for escaping variables varies from driver to driver.
Here is a PDO example:
$preqry = "INSERT INTO mytable (id,name) VALUES (23,?)";
$stmt = $pdo->prepare($preqry);
$stmt->bindparam(1,$name);
$stmt->execute();
failing to see what you database abstraction layer ($this->db) does, here's the adjusted code from example1 from the mysql_fetch_assoc documentation
<?php
// replace as you see fit
$sub1 = 'CS1';
// replace localhost, mysql_user & mysql_password with the proper details
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = 'SELECT `dSubject_id` ';
$sql .= 'FROM `tbl_subject_details` ';
$sql .= "WHERE `dSubjectCode` ='$sub1';";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['dSubject_id'];
}
mysql_free_result($result);
?>
Let me know what the output is, I'm guessing it will say: 6
Is it CodeIgniter framework you're using (from the $this->db->query statement). If so, why don't you try:
$this->db->where('dSubjectCode',$sub1);
$query = $this->db->get('tbl_subject_details');
If this doesn't work, you've got an error earlier in the code and $sub1 isn't what you expect it to be.

Categories