I'm converting a site from MySQL to Postgres and have a really weird bug. This code worked as-is before I switched the RDBMS. In the following loop:
foreach ($records as $record) {
print "<li> <a href = 'article.php?doc={$record['docid']}'> {$record['title']} </a> by ";
// Get list of authors and priorities
$authors = queryDB($link, "SELECT userid FROM $authTable WHERE docid='{$record['docid']}' AND role='author' ORDER BY priority");
// Print small version of author list
printAuthors($authors, false);
// Print (prettily) the status
print ' (' . nameStatus($record['status']) . ") </li>\n";
}
the FIRST query is fine. Subsequent calls don't work (pg_query returns false in the helper function, so it dies). The code for queryDB is the following:
function queryDB($link, $query) {
$result = pg_query($link, $query) or die("Could not query db! Statement $query failed: " . pg_last_error($link));
// Push each result into an array
while( $line = pg_fetch_assoc($result)) {
$retarray[] = $line;
}
pg_free_result($result);
return $retarray;
}
The really strange part: when I copy the query and run it with psql (as the same user that PHP's connecting with) everything runs fine. OR if I copy the meat of queryDB into my loop in place of the function call, I get the correct result. So how is this wrapper causing bugs?
Thanks!
I discovered that there was no error output due to having my php.ini misconfigured; after turning errors back on I started getting output, I got things like18 is not a valid PostgreSQL link resource. Changing my connect code to use pg_pconnect() (the persistent version) fixed this. (Found this idea here.)
Thanks to everyone who took a look and tried to help!
Related
I'm trying to do a simple query:
SELECT
job_title,
job_description,
job_tasks,
technology_skills,
job_activities
FROM
careeryou_db3
WHERE
Job_Interests = " CIE"
It works perfectly in mysql giving me this result:
http://imgur.com/a/E9yv3
However, when I use this in my PHP it returns an empty data set. I did some troubleshooting by trying to query the columns one by one and it works(returning the correct results respectively.
SELECT
job_title, job_description, job_tasks
FROM
careeryou_db3
WHERE
Job_Interests = " CIE"
Apparently, when I try to query anything from the columns of [technology_skills] OR [job_activities], the php result would return as BLANK. Does anyone have any idea why? this is strange and im kinda new to this
This is my php code:
$query = 'SELECT job_title,job_description,job_tasks FROM careeryou_db3 WHERE Job_Interests = " CIE" ';
$resultset = mysql_query($query, $connection);
$records = array();
while($r = mysql_fetch_assoc($resultset)){
$records[] = $r;
}
echo json_encode($records);
I can't see any error on your sql syntax. Can you check the mysql logs for better error information?
See here for details
https://dev.mysql.com/doc/refman/5.7/en/error-log.html
[mysqld]
log_error=/var/log/mysql/mysql_error.log
general_log_file=/var/log/mysql/mysql.log
It would help how you call the mysql, place the query build code as example.
It might be worth adding these lines for extra debugging to ensure your connection and query is successful.
$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)) {
....
It is because of the data in those columns that are conflicting with the PHP. Apparently this "—" cannot get parse into PHP which explains why the query works only in phpMyAdmin and not my PHP script.
Just while playing around with Querying in PHP i ran into some trouble. The title of this post explains the problem. When i run a query in PHPMyAdmin the results will be different from the results i get in the PHP program itself. Here is the code i am using. Sorry if it looks a little odd i've been cutting and pasting things all over the place in a frantic attempt to get it working.
$connect = array('username'=>'root', 'host'=>'127.0.0.1', 'password'=>'');
$link = mysql_connect($connect['host'], $connect['username'], $connect['password']) or die('Error creating link: ' . mysql_error());
mysql_select_db('testing_pages', $link) or die('Error connecting to database: ' . mysql_error());
$sql = "SELECT `name` FROM `names`";
$query = mysql_query($sql, $link) or die('Query Failed! Check error:<br/><br/>' . mysql_error());
$query_2 = mysql_fetch_array($query);
$query = $query_2;
$loop = count($query);
$count = 0;
while($count <= $loop) {
echo $query[$count] . '<br/>';
$count++;
}
see, what im trying to get it to do is read all the names, pop it into an array, then print them out with a while loop. But it only seems to return 1 result and thats the first name in the databse. but when i run the EXACT query through phpmyadmin it will return every name in the database... Another odd thing, when using the 'count' function to get the number of values in the array is claims that there are 3 values, but during the loop it just prints out the first name, then for the second two it returns an 'Undefined index'.
Hope i dont seem like a noob right now... And i hope i explained everything well. Thanks to anyone who can help.
mysql_fetch_array fetches one row in the form of an array. Here are the docs.
And pay attention to that big warning message at the top of the page when you read the docs...
I have a problem with an INSERT query.
Here is the problem:
Yesterday I was using this code to upload data, it was working fine. Today, when I hit submit on the form, it just shows a blank page. No errors, just blank. Nothing in the error log. All SELECT queries are working fine, so the SELECT Count(id) query still works.
Here is what I have tried:
Re-uploading to server
syntax adjustments eg '".$v.'" instead of '$v'
adding print lines to check that none of the variables are null. All is okay, all data is present just before the INSERT query.
Test insert via PHP my admin, all okay
The function call is correct - it is and remains unchanged from Yesterday
The function takes a list of species, a family and a genus, then adds them to the database.
Here is the code (the un-santised version - both were working yesterday):
error_reporting(E_ALL);
ini_set('display_errors', '1');
function submit($family, $genus, $species){
//require statement
require 'databaseConnect.php';
//get num of species
if(!($result = mysql_query("SELECT Count(id) as num FROM speciesList", $connection))) mysql_error();
$nums = mysql_fetch_row($result);
$num=$nums[0];
//parse species
$holder="";
$array = Array();
while(strlen($species)!=0){
if($species[0]==';'){
$array[] = $holder;
$holder="";
}else{
$holder = $holder . $species[0];
}
$species=substr($species, 1);
}
foreach($array as $v){
$num++;
if(!(mysql_query("INSERT INTO speciesList VALUES($num, '$family', '$genus', '.$v')", $connection))){
mysql_error();
}else{
print "success ";
}
}
mysql_close($connection);
}
Thank you very much in advance, this problem is rather mysterious to me!
Em
You never ever want to use string replacement with parameters to build SQL statements as it leaves you vulnerable to SQL injection attacks. Instead, bind your parameters.
Your code isn't returning an error because you call mysql_error() and ignore the return value. It returns the error string, so you want your code to be more like this:
if(!(mysql_query("INSERT INTO speciesList VALUES($num, '$family', '$genus', '.$v')", $connection))){
print_r( mysql_error() );
}else{
print "success ";
}
If you need help understanding the error once you see it, please post it here.
if(!(mysql_query("INSERT INTO speciesList VALUES($num, '$family', '$genus', '.$v')", $connection))){
echo mysql_error();
}else{
There maybe other things that are amiss, but the mysql_error() function returns a string. Your script needs to take some action to display the string.
I find that a better way of doing this is to construct the variables separately, so they can be displayed. And I'm not sure you want that dot before $v. See if this makes sense to you.
foreach($array as $v)
{
$num++;
$sql = "INSERT INTO speciesList VALUES($num, '$family', '$genus', '$v')";
$res = mysql_query($sql);
if (!$res) die("FAIL: $sql BECAUSE: " . mysql_error());
echo "<br/>SUCCESS: $sql";
}
I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);
I am running a query with a mysql stored procedure :
$AddProf_qr = mysql_query("call AddStudent('$d_Pass', '$d_Titl', '$d_Firs', '$d_Midd', '$d_Last', '$d_Addr', '$d_City', '$d_Stat', '$d_County', '$d_Zipc', $d_Gend, '$d_Birh', '$d_Phom', '$d_Phoh', '$d_Phoo', '$d_Email', '$d_Webs', '$d_Natn', '$d_Profsn', '$d_Compny', '$d_Desig', $d_ProfAcc)", $this->c_remote) or die ("first call" . mysql_error($this->c_remote));
I am supposed to get just one result from the call : ##IDENTITY = a number;
$AP_result = mysql_fetch_array($AddProf_qr);
$CurrentSID = $AP_result['##IDENTITY'];
which works fine. but when i run another mysql update query right after this, it gives an error saying :
Error: 2014 (CR_COMMANDS_OUT_OF_SYNC)
Message: Commands out of sync; you can't run this command now
i have tried inserting :
mysql_free_result($AddProf_qr);
but still the same.
The MySQL call executes fine also
the rest of the script runs without issues the above is commented out. but they don't run at the same time. My best guess is, the call is doing something that's messing this up.
Your stored procedure is returning multiple resultsets. See this post
Solution?
Use mysqli_multi_query
Stop using the ancient mysql library - the i in mysqli stands for "Improved" - with good reason.
#DMin Yes that's would work, but you'll crash the server sooner or later.
Just make the math, one resquest to a page that makes 3 * number of procedures to database!
Just think about it!
[UPDATE] solution:
$aCategory = array();
$it=0;
$res = $mysqli->multi_query( "call ListCategory();" );
if( $res ) {
do {
if ($result = $mysqli->store_result()) {
while( $row = $result->fetch_row() ) {
$aCategory[$it] =$row;
$it= $it + 1;
}
$result->close();
}
} while( $mysqli->next_result() );
}
foreach($aCategory as $row){
echo . $row[0] . " - " . $row[1] . "<br />";
}
Just wanted to add that you are ready to call the next Routine.
PS: By this way I couldn't use
echo $aCategory['category_id'] ;
//or
echo $aCategory->category_id;
//just
echo $aCategory[0]
Check out here: http://us3.php.net/manual/en/function.mysql-query.php In comments, one guy claims that he made it work by setting connection flag to MYSQL_MULTI_RESULTS (131072).
But it would be much better to use mysqli...
mysql_free_result(client->res);
while (mysql_more_results(client->conn))
{
mysql_next_result(client->conn);
}
This did the charm for me :)
Result sets returned from a stored procedure cannot be fetched correctly using mysqli_query(). The mysqli_query() function combines statement execution and fetching the first result set into a buffered result set, if any. However, there are additional stored procedure result sets hidden from the user which cause mysqli_query() to fail returning the user expected result sets.
Result sets returned from a stored procedure are fetched using mysqli_real_query() or mysqli_multi_query(). Both functions allow fetching any number of result sets returned by a statement, such as CALL.
look at official manual