PHP code not retrieving data from database? - php

I use the VirtueMart component on my site.
I have this piece of code running on Joomla 3.6:
<?php
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with
//"custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('customfield_value',
'virtuemart_product_id')));
$query->from($db->quoteName('jos_virtuemart_product_customfields'));
$query->where($db->quoteName('virtuemart_custom_id') . ' LIKE '. $db-
>quote('3'). ' AND '. $db->quoteName('virtuemart_product_id') . 'LIKE ' .
$db->quote($product->virtuemart_product_id));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more
options on retrieving data).
$results = $db->loadResult();
echo ($results);
?>
However, for some reason, it's not loading the data. I just get a blank page. On my localhost it's working fine, yet on my live site it's not loading at all.
Any reason why this could be? It's using the same database (phpmyadmin).
Hosting issue possibly?
I don't know. I've tested everything offline for a week and it all went swimmingly and then this happens. I don't see ANY errors in the console, so I don't know what could be wrong.
Thanks for reading.

This problem arises when you transfer your database to the server. because some of the servers have a different configuration for the database server like it may be running a database server on localhost:8080. so first check your DB config file for configuration.if you still found the same problem then I will suggest enabling PHP error reporting to 1 so that you can see what actually causing this problem.

Related

MySQL Returns different number of rows on localhost vs live server for the same code

I have a simple form that needs a list of stops in the textarea and returns an id for each on the right hand side. This is my screenshot on localhost...I have the same table names, column names, number of records on both localhost and live server.
Here's the screenshot of the same page with same query on live server...
Here's the code I am using on both pages
$conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
if(isset($_POST["busnumber"], $_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
$sql = 'SELECT * FROM stops WHERE stop_name LIKE :stop';
$statement = $conn->prepare($sql);
$statement->setFetchMode(PDO::FETCH_ASSOC);
foreach($stops as $stop){
$statement->bindValue(':stop', $stop);
$statement->execute();
$results = $statement->fetchAll();
foreach($results as $result){
echo $result['stop_id'].' '.$result['stop_name']."</br>";
}
}
}
As you can see, it returns the ID of the last row only on the live server. Can someone please tell me how this is possible and what I am missing?
EDIT 1
Notice what happens when I reverse the data entered in the text area
The localhost shows both the ids now
Guess what the server shows after reversing? Only the LAST ROW!
You don't need setFetchMode(). In the time I've used PDO I always had the best results with just using bindParam() and fetch() with the most default setup of PDO, which means just setting the errormode to exception and charset to utf8 like this:
try
{
$con = new PDO("mysql:host=".$host.";dbname=".$db_name, $user, $password);
}
catch(PDOException $e){
die("ERROR ". $e->getMessage());
}
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->exec("SET NAMES utf8");
Fetching any results like this
while($r = $statement->fetch())
{
echo $r['id'];
}
Any time when someone has used a different set up, I've noticed they've faced problems.
Try this, perhaps.
This is very simple. Please check your live db via phpmyadmin if you have access and from phpmyadmin run your queries like you are running it from php code. May be you have some restrictions of mysql or php on live. And also check your db versions on localhost and live with php versions too. Let me know the results of phpmyadmin queries thanks!
Just guessing the problem. I don't really think if this answer is correct. So please pardon me in advance.
PDOStatement::fetchAll() returns an array that consists of all the rows returned by the query. From this fact we can make two conclusions:
This function should not be used, if many rows has been selected. In
such a case conventional while loop ave to be used, fetching rows
one by one instead of getting them all into array at once. "Many"
means more than it is suitable to be shown on the average web page.
This function is mostly useful in a modern web application that
never outputs data right away during fetching, but rather passes it
to template.
Source: PDO Tutorial
I FIXED the error. I have answered it in detail on a different post and I am linking to that post from HERE Thank you all for your time and answers

Sphinxsearch periodically throws error searching an rt-index via zf2 db adapter

I'm having an intermittent problem with quite a complex search system. Every once in a while a PHP Daemon I wrote, which adds new content to our database and an RT index for sphinx throws a mysterious exception.
Message is simply "Statement could not be executed".
The code that causes it is (trimmed):
<?php
$itemIds = Array( 79555 );
$index = 'doc';
$adapter = $this->dbAdapter;
$qi = function($name) use ($adapter) {
return $adapter->platform->quoteIdentifier($name);
};
$checkSql = '
SELECT * FROM
'. $qi( $index ) . '
WHERE
id = ' . (int)$itemIds[0];
$checkStatement = $this->dbAdapter->query($checkSql);
$result = $checkStatement->execute();
The exception doesn't seem to occur on any particular trigger, but persists from the time it's first thrown to the time I restart the daemon. I've outputted the sql generated by Zend\DB\Adapter and bar ids being different, there seems to be no diference in the queries from ones that succeed to ones that fail.
There's no associated error in the sphinx logs (that I can see) and if I load neutron/sphinxsearch-api/sphinxapi.php and run GetLastError() it returns a blank string.
My thinking is that it's a connection error - or possibly a misconfiguration with the sphinx config making it timeout, but I'm not sure.
This sounds like you are using persistant connections. At times a connection might be dropped, but your code doesnt account for this, and is still trying to use a connection that has been closed. Maybe try checking for the error, and if get it, reconnects.
In short, make the code resilient to the connection occasionally having been closed.

Moving website to another local host to try - no errors, but no data is shown

This is my first time transferring my local dev site to another local site to test out, and can't access the database in the new site. Both computers are running XAMPP on Macs. The test site has successfully installed XAMPP, and has placed database files under Applications/XAMPP/xamppfiles/var/mysql. The test user is able to start Apache and MySQL, and see database files in PHPMyAdmin. The test user is also able to access the local web site with no error messages.
EDIT: The database files were copied over by copying/zipping the file on my end, and unzipping/dropping the copied files on the test end.
However, the local web site does not seem to see the database. Pages that are supposed to return data just show the default "sorry, we're sold out" message or show "image not found" graphics, and the admin is unable to log in.
The index page calls
include_once "common/base.php";
which consists of
<?php
// Set the error reporting level
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Start a PHP session
session_start();
$_SESSION['docroot'] = $_SERVER['DOCUMENT_ROOT'] . '/mysite/';
// Include site constants
include_once $_SERVER['DOCUMENT_ROOT'] . "/inc/constants.inc.php";
if ( !isset($_SESSION['token']) )
{
$_SESSION['token'] = md5(uniqid(rand(), TRUE));
$_SESSION['token_time'] = time();
}
// Create a database object
try {
$dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
$_db = new PDO($dsn, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
?>
If there was a connection problem, I would expect to see an error message returned, which I can verify by changing the constants in inc/constants.inc.php to bogus values. So I don't believe there's a connection problem.
If you were in my position, what would you check?
EDIT: I just found out about the Export function in PHPMyAdmin. I'm going to try deleting the db files that were copied over, exporting the files from PHPMyAdmin, and then importing them in the test machine.
EDIT: I just had the test machine do a simple
$sql = "SELECT FirstName From users";
$stmt = $_db->prepare($sql);
$stmt->execute();
$aaData = array();
while($row = $stmt->fetch(PDO::FETCH_NUM)){
$aaData[] = $row;
}
$stmt->closeCursor();
print_r($aaData);
on the index page, it shows the correct list of users. So the connection is good,
and there's an issue elsewhere. Would y'all say that I still need to delete the copied db and use the "correct" way (export/import), or is that a waste of time?
FINAL EDIT: I did redo the move using Export/Import and everything is working well now. Thanks to all.
First off, zipping files in the mysql data directory and moving them is not the best way to go. It can work if you have completely flushed/shut down the mysql server before moving them. You are better off using mysqldump or a similar tool to move entire databases at a time.
It sounds to me like you moved over your app's database files, but you probably forgot to add the user/password credentials to the new MySQL setup. You mentioned you use phpMyAdmin, so when you login on the other machine click the "Privileges" tab and make sure it matches up with the Privileges tab on your dev machine.
If it's not that, then it is entirely likely that by zipping and copying the files some/all of the tables were corrupted. Try using phpMyAdmin's Export and Import capabilities to move the database over. If the data is very large let me know and I can give you some command line entries to run.
Hope this helps.

Can't access the SQLite database with MAMP and PHP

I have been learning how to program websites lately and the time has come for me to add a database. I have in fact already successfully created a MySQL database and interacted with it with PHP.
My problem is I can't seem to access a SQLite database file with it. I am using MAMP to host locally for now. Here is a snippet of the code I am using to access the db and find and print out a value stored on it.
<?php
$dbhandle = sqlite_open('/Applications/MAMP/db/sqlite/Users');
if ($dbhandle == false) die ('Unable to open database');
$dbquery = "SELECT * FROM usernames WHERE username=trevor";
$dbresult = sqlite_query($dbhandle, $dbquery);
echo sqlite_fetch_single($dbresult);
sqlite_close($dbhandle);
?>
As you have access to the database (your code doesn't die), I'd say there's got to be an error later ;-)
Looking at your SQL query, I see this :
SELECT * FROM usernames WHERE username=trevor
Are you sure you don't need to put quotes arround that string ?
Like this :
SELECT * FROM usernames WHERE username='trevor'
Also, notice that sqlite_fetch_single will only fetch the first row of your data -- which means you might need to use sqlite_fetch_array or sqlite_fetch_object if you want to access all the fields of your resulset.

Problem using php ODBC functions from within a Joomla article

I am new to Joomla and new to php (wish I was so new in age too). I have installed joomla on a local apache webserver. I am trying to use some php code in a joomla article in order to fetch some data from a Sybase ASE 12.5 database. I installed sourcerer and started to try an ODBC connection using a system DSN (which I verified it is working):
{source}
<?php
echo 'This text is placed through <b>PHP</b>!';
echo '<p>';
echo '</p>';
$conn = odbc_connect('myDSN', 'sa', 'myPassword') or die('Could not connect !');
echo 'Connected successfully';
$sql = 'SELECT day, name FROM my_table where month = 1';
odbc_close($conn);
?>
{/source}
The above code doesn't do much, but this is how far I can get without problems. I refresh the joomla page and I see inside the article's text:
...
This text is placed through PHP!
Connected successfully
...
Seems ok, the connection obviously established (I verified this by stopping the sybase service and getting the "Could not connect" message). Then I added one more line, just below the $sql assignment.
$rs = odbc_exec($conn,$sql);
I refresh and ...I see nothing coming from the script (not even the "This text is placed through PHP!").
Obviously, I see nothing if I include code to echo the contents of $rs. I also tried this but in vain.
if (!$rs)
{exit("Error in SQL");}
Once I add the odbc_exec command, the entire script ceases working.
In php.ini I read:
; Windows Extensions
; Note that ODBC support is built in, so no dll is needed for it.
Do you have any idea what is going wrong?
UPDATE
Connecting to a MySQL database using code like this, works like a charm.
To answer your question
Is this the correct way to get data
from another database in to an article
or should I use some plug-in to do
that?
The correct way is to use JDatabase object which you get by JFactory::getDBO() or JDatabase::getInstance(), see Joomla JDatabase documentation.
$db = JDatabase::getInstance( $databasConfigArray );
$db->setQuery('your query');
$data = $db->loadObjectList();
Here is a good tutorial showing how to connect to multiple databases in Joomla, there is even source code for helper class.
Also look at this thread Connecting to 3rd party databse in Joomla!?

Categories