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.
Related
I have the following sql statement
$sql=
"SELECT wr.SortOrder, wr.webRequests_ID, wr.PQ_ID, pq.QText,wr.The_Answer, wr.webtmporders_detail_ID
FROM tbl_Preference_Questions as pq
INNER JOIN tblwebtmporders_detail_Requests as wr ON pq.PQ_ID = wr.PQ_ID
WHERE wr.webtmporders_detail_ID = 42569
ORDER BY wr.SortOrder";
I get the records thru a function. the varialbe $mdbFilename is the path to the Access database.
$conn=odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename",'','',SQL_CUR_USE_ODBC);
$result_id = odbc_exec($conn, $sql);
$results = all_odbc_rows($result_id);
function all_odbc_rows($result_id)
{
$tmp_arr = "";
while($row = odbc_fetch_array($result_id)){
// this needs to be in my program code because ODBC / Access DB query will not accept escaping of single quotes. single quotes
// must be replaced by two single quotes for the sql passed to access via ODBC to work.
foreach ($row as $k => $value)
{
$v = strip_tags($value);
$row[$k] = str_replace("\\","",str_replace("'","''",$v));
}
$tmp_arr[] = $row;
}
return $tmp_arr;
}
yet I am getting the following PHP warning
odbc_fetch_array(): SQL error: [Microsoft][ODBC Microsoft Access Driver] The specified field '`PQ_ID`'
could refer to more than one table listed in the FROM clause of your SQL statement., SQL state S1000
in SQLGetData
If I run this sql in Microsoft Access Query builder, it returns 7 records with no problem. Yet I get an error when I run the sql statement thru ODBC in PHP. I get the warning, and ODBC does not return any records. Cannot work out why this join is not working?
I tried getting rid of the wr. and the pq. table identifiers and replaced them with the full table names in the sequel statement, but this did not work.
Any one have any ideas?
Thank you.
btw, if I take the wr.PQ_ID field out of the sql statement, ODBC can run the query succesfully.
This is very strange.
Here is the query builder in Access for this query I am trying to run in ODBC PHP
And SQL statement in in query builder in MS-Access
And the Result
So It works in MS Access, but not in ODBC call from PHP
weird.
Well, I found someone on php.net that brought up the same issue. Yet they were using SQL Server. I am using MS-Access .mdb file. They were able to use aliases with SQL Server database engine. Aliases have not worked for me. So I think the solution is that the joining fields / columns, must have different names, if using MS-Access Database, for ODBC odbc_fetch_array() or odbc_fetch_object() to work in a join sql statement.
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.
We have a uni student doing work experience at the moment and he's doing a Wordpress prototype for us (as we have neither Wordpress or PHP experience).
It's running on a Windows server and while Wordpress itself is running in mySQL, as all our existing databases are in MS SQL Server 2005/2008 and he's trying to call a stored procedure in a php page using this code:
$connection = odbc_connect('DB', 'UNAME', 'PWORD');
$request = odbc_prepare($connection, "CALL ProcName(?, ?, ?)");
if(!$request) die("Could not prepare statement:" . odbc_errormsg());
$result = odbc_execute($request, array("var1", "var2", "var3"));
if(!$result) die("Could not execute statement:" . odbc_errormsg());
The stored procedure is like this:
ROCEDURE [dbo].[ProcName]
(#option1 varchar(50),
#option2 varchar(50),
#option3 varchar(50))
AS
... lots of logic end with...
select * from tblName
The stored procedure is used both by .net pages and Livelink CMS pages and works correctly but when we try to call it from php, it errors with:
"odbc_execute(): SQL error: [Microsoft][ODBC SQL Server Driver]Invalid parameter number, SQL state S1093 in SQLDescribeParameter in C:\inetpub\wordpress\test.php on line 29"
Strangely, if we rename the procedure call to a non existant stored procedure, it errors with exactly the same thing rather than a stored procedure cannot be found type of error.
We can run sql directly i.e. "select * from etc" and it will return data but we can't call stored procedures (which we use for everything of course!).
Any idea where he could be going wrong?
As I can see from the error message, the error should come from the ODBC driver, because from it's perspective the parameter number differs from prepare to execute statements.
Ask your student to try this approach:
$parms=array("var1", "var2", "var3");
if (!odbc_execute($request, &$parms)) die("odbc_execute failed");
I got the same error when I was doing an native SQL query from Java EE/Hibernate. I was querying "SELECT Count (1) From Table" and I made the mistake of including a mapping class as a parameter. COUNT(1) returns an integer, so it doesn't need to be mapped. Hope that helps.
I'm having a problem with a query prepared in PHP with PDO. The code:
$link = new PDO("mysql:dbname=$dbname;host=127.0.0.1",$username,$password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $link->prepare("SELECT locality_name FROM :passedday GROUP BY locality_name ORDER BY locality_name DESC");
$query->bindParam(":passedday",$day); //Where day is, well, a day passed to the script elsewhere
$query->execute();
$result = $query->fetchAll();
$link = null;
//Do things with the $result.
The error message I am getting is:
SQLSTATE[42000]: Syntax error or access violation: 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 ''05_26_09' GROUP BY locality_name ORDER BY locality_name DESC' at line 1
When I execute the query on the server directly, it returns the appropriate result set without any problem. Any ideas what I'm doing wrong?
TIA.
Edit:
$day is passed as a GET argument. So, http://127.0.0.1/day.php?day=05_26_09 leads to $day = $_GET['day'];.
If 05_26_09 is supposed to bet the table's name, then I guess you've an escaping problem. Is your local operating system different from the live server?
I don't think you can use bindValue()/bindParam() for something else than values (eg. table name, field name). So I'm a bit suprised, that it works on your local system.
PDO uses mysql's C-API for prepared statements.
http://dev.mysql.com/doc/refman/5.0/en/mysql-stmt-prepare.html says:The markers are legal only in certain places in SQL statements. [...] However, they are not allowed for identifiers (such as table or column names)As a rule of thumb I use: "if you can't wrap it in single-quotes in an ad-hoc query string you can't parametrize it in a prepared statement"
I use SQL_CALC_FOUND_ROWS in Mysql SELECT statement, to get the number of lines my SELECT would return without a LIMIT clause.
$sql = new mysqli('localhost', 'root', '');
$sql->select_db('mysql');
$s1 = $sql->query('select SQL_CALC_FOUND_ROWS * from db limit 0, 3');
$s2 = $sql->query('select FOUND_ROWS()');
if($row = $s2->fetch_row()) printf('%d/%d', $s1->num_rows, $row[0]);
On my WinXP dev station it return 3/0 everytime for several weeks. When I use another MySQL server from my station it return 3/0 too.
On anothers PC the same code runs fine, and return the correct number (3/17 for example, if I have 17 records in mysql.db table). Every XP PC have the same PHP/Mysql version, and it ran fine in the past on my PC
Using Mysql Query Browser with the same SQL queries I get the right number.
Could anyone give me an idea of solution, without re-install all?
Sorry, my previous request was awfully unclear.
Thank you.
When I ran something analogous to your example on the mysql command line, it would work; but running it from php, it failed. The second query has to "know about" the first one, so I figure somehow that persistence/memory linking the two queries was getting messed up by the php.
(It turns out that Wordpress uses this type of query to do its pagination - so our larger problem was that the pagination in a wordpress install suddenly stopped working when we moved to php 5.2.6 ... eventually tracked it down to the FOUND_ROWS()).
Just for the sake of posting for people who may run into this in the future... for me it was the php setting "mysql.trace_mode" - this defaulted "on" in 5.2.6 instead of "off" like previously, and for some reason prevents the FOUND_ROWS() from working.
As a "fix", we could either put this in every php page (actually, in a common "include"):
ini_set("mysql.trace_mode", "0");
or add this to the .htaccess:
php_value mysql.trace_mode "0"
Thanks again,
Jerry
Are you using a MySQL query method that allows for multiple queries.
From MySQL documentation.
To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward
Example:
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
Also just for fun, there's a great discussion about the race condition of FOUND_ROWS()'s usage here.
Another way would be to use mysqli_multi_query as stated in the PHP manual by passing both queries containing SQL_CALC_FOUND_ROWS and FOUND_ROWS separated with a semicolon
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM db limit 0, 3;";
$query .= "SELECT FOUND_ROWS()";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
The quickest solution is to subquery your actual query like this:
SELECT SQL_CALC_FOUND_ROWS * FROM (SELECT whatever FROM whatever WHERE whatever LIMIT whatever) ax;
select FOUND_ROWS();
Now you will get the correct results. I think the main reason being that SQL_CALC_FOUND_ROWS mainly tracks rows found (i.e. without LIMITS) not rows returned.
I had the same issue. The solution was stupid, I was using $wpdb->query instead of $wpdb->get_var. So you want to do
$wpdb->get_var('select FOUND_ROWS()');
if you're on WordPress
Well, it was a problem with mysql php extension bundled with php 5.2.6. Mysqli run fine, and another php version too.
Sorry for noise and unclear question.
If you have the same problem, my advice is to re-install PHP or change version.