I am querying a mysql database with php but cannot get it to work on my iMac. In particular, php is unable to connect to the mysql DB. It connects to mysql and selects the DB but then fails. See code below:
if (!mysql_connect($db_host, $db_user, $db_pwd)){
die("I cannot connect to database");
}
if (!mysql_select_db($database)){
die("I cannot select database");
}
$sql = "SELECT FROM ${table} ORDER BY $sql_orderBy";
$result = mysql_query($sql);
if (!$result) {
die("I cannot execute query to show fields from Table: {$table}. Query failed.");
}
For reference, I installed apache/mysql/php with macports. The same php code works on my laptop (same installations), and the query works when I invoke it from within mysql on both computers. All variables are declared. Something with the system config is my best guess, but I even went through a uninstall/install.
Any help would be appreciated!
Your issue is ${table} . This should be {$table} or better still, ".$table."
You also need to say what you are SELECTING:
So:
$sql = "SELECT * FROM ".$table." ORDER BY ".$sql_orderBy;
You can discover issues by using Mysql_error() at the end of the query, for example:
mysql_query($sqlString) or die("line: ".__LINE__.":".mysql_error());
this will output a clear error message regarding your SQL statement. This is not for production and public situations but for development.
Also:
MySQL is deprecated and is no longer supported by PHP or the wider community, it is VERY strongly recommended you take up MySQLi or PDO and use these methods as they are much stronger, less flawed and more efficient delivery of results. They will also be supported in future updates and developments whereas MySQL will not.
Related
I work with xampp. I performed MySQL connection:
$connection = mysql_connect($host , $user , $passw);
mysql_select_db($db, $connection);
I received output with echo command (by check the boolean returned values) that connection is established and the database $db is found.
But the simplest query like:
$query = mysql_query("SELECT * FROM 'users'");
returns false. How can I debug why?Thanks.
An obligatory update: as mysql ext is no more, here are answers for two remaining MySQL APIs which I written on my site based on the experience from answering 1000s questions on Stack Overflow:
How to report errors in mysqli
How to connect to MySQL using PDO (with the aim of the proper error reporting).
In short, for mysqi the following line have to be added before mysqli_connect() call:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
while for PDO the proper error mode have to be set, for example
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
As of the old mysql ext,
To get an error from mysql_query() you have to use mysql_error() function.
So always run all your queries this way, at least until you develop a more advanced query handler:
$query = "SELECT * FROM 'users'";
$result = mysql_query($query) or trigger_error(mysql_error()." ".$query);
the problem with your current query is 'users' part. Single quotes have to be used to delimit strings while for the identifiers you have to use backticks:
SELECT * FROM `users`
In order to see these errors during development, add these lines at the top of your code to be sure you can see every error occurred
ini_set('display_errors',1);
error_reporting(E_ALL);
on the production server, however, the value on the first line should be changed from 1 to 0
Use the mysql_error() function:
$query = mysql_query("SELECT * FROM 'users'") or die(mysql_error());
EDIT: Per Col. Shrapnel's comment: you should never use die() outside of a test environment. In general it's bad practice when writing code that's even intended for production.
Here is some more information: http://www.phpfreaks.com/blog/or-die-must-die
Based on Your Common Sense answer this is an object oriented style:
$query = "SELECT * FROM 'users'";
$result = $mysqli -> query($query) or trigger_error($mysqli -> error." ".$query);
I am maintaining a server that runs for around 1 year. Nothings gonna be wrong previously. However, suddenly, there is an error in mysql_insert_id(), which returns 0, instead of normal row id from the database. Here's are the core of the code.
$sql = "INSERT INTO $db_table (name,email) VALUES('$name','$email')";
mysql_query($sql);
$current = mysql_insert_id();
Also notice that even if there are no changes in the code, the program runs smoothly again after the error has happened. It seems strange to me.
Here is my possible explanation. Since I am hosting in a public server, where many are using the same MYSQL server. Will it be that when mysql_query($sql), the server then swap the process and let another guy to run another SQL command, which may be for example, a SELECT statement, and after their execution, it swaps back to my own code and continue executing, which results in 0?
Please help. Thanks.
to be sure use the resource_identifier as parameter in mysql_queryand mysql_insert_id.
If you don't, the last connection to the mysql server is used, as you thought.
$resource = mysql_connect(...);
$sql = "INSERT INTO $db_table (name,email) VALUES('$name','$email')";
mysql_query($sql, $resource);
$current = mysql_insert_id($resource);
Please consider using mysqli oder PDO since mysql_* functions are deprecated and are going to be removed in future PHP-Versions
I have this SQL query:
SET #date_shift = DATE_SUB(NOW(), Interval 60 MINUTE);
SELECT hinfo.idx,
hinfo.host_idx,
hinfo.processor_load,
hinfo.memory_total,
hinfo.memory_free,
hnames.idx,
hnames.name,
disks.hostinfo_idx,
disks.id,
disks.name,
disks.size,
disks.freespace,
hinfo.probetime
FROM systeminfo.hostinfo AS hinfo
INNER JOIN systeminfo.hosts AS hnames
ON hnames.idx = hinfo.host_idx
INNER JOIN systeminfo.disksinfo AS disks
ON disks.hostinfo_idx = hinfo.idx
WHERE hinfo.probetime > #date_shift AND
hinfo.probetime = (SELECT MAX(probetime) FROM systeminfo.hostinfo AS hi
WHERE hi.probetime > #date_shift AND hi.host_idx = hinfo.host_idx)
GROUP BY disks.id,
hnames.name
ORDER BY hnames.name,
disks.id;
and i try to execute it in php code. I tried mysql, mysqli and pdo. Ma last code is following:
$db = new PDO("mysql:host=".$this->ip.";dbname=".$this->dbname.";charset=utf8", $this->username, $this->password);
$result = $db->query($query);
$fetch_data = $result->fetchAll(PDO::FETCH_ASSOC);
or
mysql_connect($this->ip, $this->username, $this->password);
mysql_query('SET NAMES utf8;');
mysql_select_db($this->dbname);
$result = mysql_query($query);
PHP connects correcly to the database. Simple queries, like select * from tablename works. But this query returns NO data but error:
1064 : You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'SELECT hinfo.idx, hinfo.host_idx, hinfo.processor_load,
hinfo.memory_total, ' at line 2
The same query, executed in the database client works perfectly (it's not a slow query, it takes less than 10 ms to perform it).
Moreover, when i try to print the query directly from this function on a web page and paste it into mysql client - it works perfectly as well! I can't find any special character in hex viewer i tried to force utf-encoding, nothing.
Any ideas? Test i could perform? Thanks in advance!
Try to execute this as two seperate statements. Running queries from GUI tools or command line tools differ from embedding queries in code. So it works in database tool, but not in php code.
The mysql adapter for PHP can only handle one query at a time. You should indeed run the queries separate from each other.
"#date_shift" will be available in the second query, assuming your connection to mysql does not get destroyed between the two queries.
i am trying to connect to two databases to create a search engine for a couple of my databases. Heres a test code. can someone tell me what i am doing wrong or if it is possible. thanks.
mysql_connect("localhost","user","pass");
mysql_select_db("db1");
mysql_select_db("db2");
$search=mysql_query("SELECT * from db1.repairs, db2.order from db1,db2");
while($row=mysql_fetch_array($search)){
echo $row['first_name']." ".$row['esn']." ".$row['order_type']."<br>";
}
You can query across databases if you specify the database name before the table name like this
SELECT a.col1, b.col2
FROM db1.table1 AS a
INNER JOIN db2.table2 AS b ON a.someIdFromA = b.someIdFromB
As Korcholis mentions the problem is in your select. Also you do not want to use the mysql_* functions if you can avoid it. PDO or MySqli are preferred.
Edit
At least this works using MySQL. I would bet it works for most other RDBMSes as well, but I don't have others handy to test and I can't say if this conforms to SQL standards or not. Comments anyone?
You can use
<?php
$db1 = mysql_connect("localhost","user","pass");
$db2 = mysql_connect("remote","user","pass");
mysql_select_db("db1", $db1);
mysql_select_db("db1", $db2);
$query1 = mysql_query("USE somedatabase", $db1);
$query2 = mysql_query("USE otherdatabase", $db2);
Or try with a class that handles these connections in a different instances
http://www.joni2back.com.ar/programacion/php-class-for-mysql-databases/
mysql_connect returns a $resource. You can connect twice and select a database with each one (in fact, you can select a database from the connect itself), and then use each connection.
However, your problem is that your SELECT is incorrect. You are trying to select fields from tables from databases, which is not correct. In fact, you cannot fetch two different databases in a so fancy way, because they are considered two sets of information independent and unrelated between them. That's why tables exist, to fit that problem.
This other answer, however, may have a solution.
Otherwise, you could connect to each database using two mysql_connect and two resources, fetch the values, and cross them yourself. Not the best option, I know, but an answer that could fit your needs.
PS: If you are beginning the project right now, switch to Mysqli or PDO. Mysql is deprecated.
Try to review this, and maybe you can't query a database with querying FROM:
<?php
$con1 = mysqli_connect("$hostname", "$user1", "$password1", "$db1");
if (mysqli_connect_errno($con1)) {
echo mysqli_connect_error();
}
$con2 = mysqli_connect("$hostname", "$user2", "$password2", "$db2");
if (mysqli_connect_errno($con2)) {
echo mysqli_connect_error();
}
$search1 = mysqli_query($con1, "SELECT * from $db1table");
$search2 = mysqli_query($con2, "SELECT * from $db2table");
/* Other PHP codes here */
mysqli_close($con1);
mysqli_close($con2);
?>
You can even improve this code, nor minimized it!
I work with xampp. I performed MySQL connection:
$connection = mysql_connect($host , $user , $passw);
mysql_select_db($db, $connection);
I received output with echo command (by check the boolean returned values) that connection is established and the database $db is found.
But the simplest query like:
$query = mysql_query("SELECT * FROM 'users'");
returns false. How can I debug why?Thanks.
An obligatory update: as mysql ext is no more, here are answers for two remaining MySQL APIs which I written on my site based on the experience from answering 1000s questions on Stack Overflow:
How to report errors in mysqli
How to connect to MySQL using PDO (with the aim of the proper error reporting).
In short, for mysqi the following line have to be added before mysqli_connect() call:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
while for PDO the proper error mode have to be set, for example
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
As of the old mysql ext,
To get an error from mysql_query() you have to use mysql_error() function.
So always run all your queries this way, at least until you develop a more advanced query handler:
$query = "SELECT * FROM 'users'";
$result = mysql_query($query) or trigger_error(mysql_error()." ".$query);
the problem with your current query is 'users' part. Single quotes have to be used to delimit strings while for the identifiers you have to use backticks:
SELECT * FROM `users`
In order to see these errors during development, add these lines at the top of your code to be sure you can see every error occurred
ini_set('display_errors',1);
error_reporting(E_ALL);
on the production server, however, the value on the first line should be changed from 1 to 0
Use the mysql_error() function:
$query = mysql_query("SELECT * FROM 'users'") or die(mysql_error());
EDIT: Per Col. Shrapnel's comment: you should never use die() outside of a test environment. In general it's bad practice when writing code that's even intended for production.
Here is some more information: http://www.phpfreaks.com/blog/or-die-must-die
Based on Your Common Sense answer this is an object oriented style:
$query = "SELECT * FROM 'users'";
$result = $mysqli -> query($query) or trigger_error($mysqli -> error." ".$query);