PHP: connected to database, but mysql_query fails - php

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.

Related

This mysql_connect Attribute seems to old how can I replace them?

I cannot connect to my Data Base using this way:
mysql_connect("localhost","root","") or die("1");
mysql_select_db("database") or die("2");
After the connection to the data base I would like to create a while loop with the elements of the data base, this is my code:
$carlistreq = mysql_query("SELECT * FROM cars WHERE brand="'.$_GET['marq'].'"") or die("3");
$count = mysql_num_rows($carlistreq);
if($count==0)
{
echo "No elements";
}
else
{
while($row= mysql_fetch_array($query))
{
//my code
}
}
The issue comes from my SQL attributes like:
mysql_connect
mysql_fetch_array
mysql_select_db
For example.
Here is the error:
Deprecated: mysql_connect(): The mysql extension is deprecated and
will be removed in the future: use mysqli or PDO instead in C:[....]
on line 2
use the mysqli-extension like this:
$mysqli = new mysqli("localhost","user","password","database") or die("1");
$sql = "SELECT * FROM cars WHERE brand='".$_GET['marq']."'";
$result = $mysqli->query($sql);
if($result){
while($row = $result->fetch_assoc()){
//do something with your $row here
}
}
http://php.net/manual/en/book.mysqli.php
Use PDO
$db = new PDO('mysql:host=localhost;dbname=databaseName', 'User' , 'password');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
Yes now servers are going to handel mysqli and PDO. Try implementing this code:
<?php
$con = mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
// Change database to "test"
mysqli_select_db($con,"test");
// ...some PHP code for database "test"...
mysqli_close($con);
?>
You can user http://php.net/manual/en/book.mysqli.php as reference to understand better how mysqli works.

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 not displaying MYSQL result

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();
}

Getting JSON From An External MySQL Database Error?

i am using this tutorial and i dont know what is error is this
<?php
header('Content-type: application/json'); // this is the magic that sets responseJSON
// Connecting, selecting database
$link = mysql_connect($dbhost, $dbuser, $dbpass)
or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname) or die('Could not select database');
switch($_POST['op']) {
case 'getAllRecords': {
$table = $_POST['table'];
$query = sprintf("SELECT * FROM %s", mysql_real_escape_string($table));
// Performing SQL query
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$all_recs = array();
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$all_recs[] = $line;
}
break;
}
}
echo json_encode($all_recs);
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
error is :- null
Warning: mysql_free_result(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/mapleleafrealities.com/test.php on line 26
This is Example
My Error
if you have any simple example of getting json from external db please give me link or code
The op POST parameter is not "getAllRecords", so you're trying to encode something that doesn't exist, and free a result that was never taken. Try putting them inside.

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