I am wanting to connect to a SQL Server Instance in my article, and I have the below syntax to do such. My issue is that when I view the article it writes
".$row['book_name']."
"; } ?>
onto the screen instead of interpreting it as part of the code. This is the code that I have, what do I need to alter so that the Joomla Article interprets this properly?
<?php
//provide your hostname, username and dbname
$host="";
$username="";
$password="";
$db_name="";
//$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
$con=mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$book_name = $_POST['book_name'];
$sql = "select book_name from book_mast where book_name LIKE '$book_name%'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['book_name']."</p>";
}
?>
EDIT
Updated to use JFactory
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('Top 1 employer')));
$query->from($db->quoteName('#[Roster].[dbo].[Employers]'));
$db->setQuery($query);
$row = $db->loadRow();
print_r($row);
But how do I pass in the server and credentials in this set-up?
EDIT 2
I have updated my code to use the JDatabaseDriver
since my Joomla Install and the server I want to query are on different instances. I added in this syntax:
<?php
$option = array(); //prevent problems
$option['driver'] = 'mysql'; // Database driver name
$option['host'] = 'db.myhost.com'; // Database host name
$option['user'] = 'fredbloggs'; // User for database authentication
$option['password'] = 's9(39s£h[%dkFd'; // Password for database authentication
$option['database'] = 'bigdatabase'; // Database name
$option['prefix'] = 'abc_'; // Database prefix (may be empty)
$db = JDatabaseDriver::getInstance( $option );
$query = $db->getQuery(true);
$query->select($db->quoteName(array('Top 1 employer')));
$query->from($db->quoteName('#[Roster].[dbo].[Employers]'));
$db->setQuery($query);
$row = $db->loadRow();
print_r($row);
?>
And now I get displayed on screen on page load everything after
getQuery(true);
What am I missing here?
mysql_*
as it's deprecated. Secondly, use the JDatabase class to connect to your database. Joomla has wrappers for a reason, so please use them. Have a read of the doucmentation: docs.joomla.org/Selecting_data_using_JDatabase