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!?
Related
We have a remote server containing a SQL MariaDB. I have to write a piece of code to be placed in that same server whose mission is to execute querys asking for data, modify that data and send it to an external api hosted in another server. When I was shown the DB, it was through ssh commands and entering sql mode inside the server rather than trough code like PHP as I have always done it before.
So, my code is to placed in the same server as the DB, brings the data, modifys some info and calls the api to upload it.
As I said, I am completely lost so my question is simple: can this be achieved? if so, how?
I've read about ssh_connect and exec, but since the code will be placed in the same server I don't think this is necessary, correct me if I am wrong. I can't place any code since I don't know how to start.
Thank you guys for all the help, I am closing the question now:
All I had to do was to use PDO as a secure way to establish a connection and to prepare and execute the querys. Remember I placed my php file in the same server that hosts the DB and note that I had to create a user and grant permissions to the DB you can find how in one of the comments above or here. Here is the code:
try {
$conn = new PDO('mysql:host=yourhostserver;dbname=dbname','user','password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
//Example of query
$stmt = $conn->prepare('SELECT GROUP_CONCAT(DISTINCT source_external_subscriber_id) AS ids FROM cdr');
$stmt->execute();
foreach ($stmt as $row) {
$string = $row['ids'];
}
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.
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.
I'm using HostMonster as my web host and I'm trying connect to a database I created using MySQL inside of HostMonster. In order to call that database in my website do I need to use PHP? Or is there a way to create a javascript OnClick function that can call the database. I'm not using ASP.Net so it's not quite as simple as I would like it. Just curious if the best solution is PHP, if so I guess I should go learn it.
what are you planning to do with the database, other than just 'calling it'? You will need some language like PHP to connect to the DB to retrieve, insert, update or delete data in the DB.
here is a code for connection MySQL from PHP using MYSQLI extension
<?php
$dba_host='localhost';
$dba_name='root';
$dba_pass='';
$dba_db='sn';
$con=mysqli_connect($dba_host,$dba_name,$dba_pass,$dba_db) or die('Connection Refused !');
$stmt=mysqli_prepare($con,"SELECT UID FROM Main");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $value);
while(mysqli_stmt_fetch($stmt))
$result[] = $value;
mysqli_stmt_close($stmt);
mysqli_close($con);
?>
Your javascript onClick function is running on the client side (in the browser) and the database is running on the server-side. You will need a server-side language to get the information from the database and send it to the browser.
You do not HAVE to use PHP to connect to a MYSQL database. Also, you can't connect to your database using only client-side javascript (ie. an onClick() function). You need to use a server side language, PHP is one choice.
To connect to a MYSQL database on hostmonster using PHP you will need to know your credentials that use to log into phpMyAdmin from your cpanel. Once you have made the connection you can then select the MYSQL database that you created. Once the database is selected you can query it using the "mysql_query" function in PHP. The following code does all of that and stores the results of the MYSQL query in a PHP variable called $result.
<?php
$con = mysql_connect("www.yourdomain.com","phpMyAdmin_username","phpMyAdmin_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql_database_name", $con);
$query = "SELECT * FROM TableName"
$result = mysql_query($query);
?>
Now you've got the results of the query inside the PHP variable $result and you can use it anyway you like.
If you put this in your 'public_html' folder and named it 'index.php' or 'index.html' this would automatically be run when someone went to www.yourdomain.com.
You can find a great tutorial series on PHP here http://thenewboston.org/list.php?cat=11.
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.