Joomla, Mysql error - php

I have uploaded a page with the code below to my joomla root directory.
<?php
$value = trim($_POST['opts']);
if ($value){
$db = "my_db";
$link = mysql_connect('localhost',$me,$my_password);
if(!$link) die("Error 1 ".mysql_error());
mysql_select_db($db);
**$query = "SELECT introtext,fulltext FROM jos_content WHERE title='$value' ";**
$result = mysql_query($query);
**if(!$result) die("Error 2 ".mysql_error());**
$obj = mysql_fetch_array($result);
$obj_f = $obj[0];
$lenght = strlen($obj_f);
$header2 = strpos($obj_f, "Did you know");
$header3 = strstr($obj_f, "Summary");
$third_part = $header3;
$first_part = substr($obj_f, 0, ($header2 - 1));
$second_part = substr($obj_f, $header2,((strpos($obj_f, "Summary")) - $header2) );
}
?>
the problem is that when i change my select(http://sanatural.co.za/sanp/test.php) i get this error message:
Error 2 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 'fulltext FROM jos_content WHERE title='Arthritis'' at line 1
The code highlighted in bold is where i think the problem might be. Please help.

Fulltext is a mysql keyword and you must escape it. Replace:
$query = "SELECT introtext,fulltext FROM jos_content WHERE title='$value' ";
with
$query = "SELECT `introtext`,`fulltext` FROM jos_content WHERE title='$value' ";

This is a bit off topic, but an easy way to use PHP in Joomla is through the PHP Component.
http://www.fijiwebdesign.com/products/joomla-php-pages.html
This allows you to put add PHP in Joomla as if it were a Joomla Component.
If you want something quick, then you can also use the PHP Module.
http://www.fijiwebdesign.com/products/joomla-php-module.html
Just install either, add your PHP, and add it to the Joomla menu.
You can then use the Joomla API which will simplify what you want to do within Joomla.
For example, your database queries could be:
// Joomla already has a connection to the DB
// available here as a Singleton in the Factory pattern
$Db =& JFactory::getDBO();
// querying the db
$Db->setQuery('SELECT `introtext`,`fulltext` FROM #__content WHERE title='.$Db->Quote($value).' LIMIT 1';
// retrieving a single row as an object
$article = $Db->loadObject();
// handle errors
if($Db->getErrorNum()) {
JError::raiseError( 500, $Db->stderr());
}
//Then accessing each column/property would look something like:
$intro = $article->introtext;
$text = $article->fulltext;
The full Database API is documented here:
http://api.joomla.org/Joomla-Framework/Database/JDatabase.html

Related

Transfotm PHP SQL to Joomla SQL query

I am moving a PHP page to my Joomla website and I was advised that I "should use Joomla's coding standards and methods for everything, this includes database queries"
My question is:
How should I transform my old PHP code regarding Joomla standards:
$query = "SELECT * FROM `TABLE 2` WHERE Power=".$input->get('Power', '', 'RAW')." AND Poles=".$input->get('Poles', '', 'RAW')."";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results))
{
extract($row);
}
?>
This is the TABLE 2 contents. I use the values of each row as a variables on my page.
Most importantly make sure to filter the input to disallow sql injections. Seems both your inputs are numbers (Power is a float and Poles possibly an int?). Also use the #__ - in table names, it will be replaced by the table prefex when you use it in joomla functions. Simplest way to transform your code would be something like:
$app = JFactory::getApplication();
$power = $app->input->getFloat('Power'); // use the correct function
$poles = $app->input->getInt('Poles'); // for the datatype you want
see here for JInput docs
$db = $app->getDbo();
//short variant
$sql = "SELECT * from `#__table 2` WHERE power = "
. $db->quote($power) . " AND poles = " . $db->quote($poles);
$db->setQuery($sql);
$result = $db->loadRowList();
foreach($result as $array){
print_r($array);
}
It should be noted that there are more useful methods for retrieving the data, loadAssoc/loadAssocList for associative arrays, loadObject/loadObjectList for objects. Check the docs for JDatabaseDriver
Alternatively you could transform the query to a "Joomla query" like:
$q = $db->getQuery();
$q->select("*")->from($q->quoteName("#__Table 2"));
$q->where("Power = " . $db->quote($power));
$q->where("Poles = " . $db->quote($poles));
$db->setQuery($q);
...
Docs to JDatabaseQuery

Update query works in php my admin but not in php script

I am having a problem with a script that im trying to create, it updates some params in a joomla cms website. If I make the updates in phpmyadmin and then press go it says :
UPDATE `websit52_rcsetch`.`u5b0y_modules` SET `params` = '{"moduleclass_sfx":"demovideos","youtube_id":"XM0aLFaij8I3","width":"300","height":"200","responsive":"1","cache":"1","cache_time":"900","cachemode":"itemid"}' WHERE `u5b0y_modules`.`id` =192;
so I think, ok il just copy that query and put it into php and change the params to what I need.
so end up with :
mysql_query("UPDATE `websit52_rcsetch`.`u5b0y_modules` SET `params` = '{"moduleclass_sfx":"demovideos","youtube_id":"XM0aLFaij8I3","width":"300","height":"200","responsive":"1","cache":"1","cache_time":"900","cachemode":"itemid"}' WHERE `u5b0y_modules`.`id` =192;")or die(mysql_error());
The problem is now on that line in Dreamweaver I am getting a red error warning on that line, but all I have done is literally copied the query into the mysqli query, so cant see why it wouldnt work ?. It says there is a syntax error, which I presume is caused by the double quotes that the params use, but im not sure if I can escape these without it effecting the query ?, or is there something else causing the problem ?.
mysql_query("UPDATE `websit52_rcsetch`.`u5b0y_modules` SET `params` = '{\"moduleclass_sfx\":\"demovideos\",\"youtube_id\":\"XM0aLFaij8I3\",\"width\":\"300",\"height":\"200\",\"responsive\":\"1\",\"cache\":\"1\",\"cache_time\":\"900\",\"cachemode\":\"itemid\"}' WHERE `u5b0y_modules`.`id` =192;")or die(mysql_error());
In Joomla synthax :
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
$db->quoteName('params') . ' = ' . $db->quote('{"moduleclass_sfx":"demovideos","youtube_id":"XM0aLFaij8I3","width":"300","height":"200","responsive":"1","cache":"1","cache_time":"900","cachemode":"itemid"}')
);
// Conditions for which records should be updated.
$conditions = array(
$db->quoteName('id') . ' = 192'
);
$query->update($db->quoteName('#__modules'))->set($fields)->where($conditions);
$db->setQuery($query);
$result = $db->query();

Executing Multiple MySQL Queries in a PHP/HTML Webpage: only first query runs

I have a webpage written in HTML. I have a dropdown list that is populated by a database utilizing a MySQL query:
<SELECT NAME = "Participant" STYLE = "WIDTH: 187" TITLE="Begin typing participant last name for fast searching." required>
<OPTION SELECTED VALUE = "">Select Participant...</OPTION>
<?PHP
$allParticipants = getall_participants();
foreach($allParticipants as &$value) {
$dt = date('Y-m-d');
$val = $value->get_id();
$optval = $dt.$val;
echo "<OPTION VALUE='",$optval,"'>";
echo $value->get_first_name()," ",$value->get_last_name();
echo "</OPTION>";
}
?>
</SELECT>
The getall_participants() looks like:
function getall_participants () {
connect();
$query = "SELECT * FROM dbParticipants ORDER BY last_name";
$result = mysql_query ($query);
$theParticipant = array();
while ($result_row = mysql_fetch_assoc($result)) {
$theParticipant = new Participant($result_row['last_name'],
$result_row['first_name'], $result_row['address']);
$theParticipants[] = $theParticipant;
}
mysql_close();
return $theParticipants;
}
And on this same page I have a textbox that is pre-filled-in by another database:
<?php
$dt = date('Y-m-d');
$participants = getall_dbParticipantEntry_byDate($dt);
foreach($participants as &$value) {
$a = $a.$value.", ";
}
echo "<INPUT TYPE='text' NAME='Participants' STYLE='WIDTH:50px;' TITLE='Participants' ";
echo "VALUE='[", $a.' ', "]'/>";
?>
That getall_dbParticipantEntry_byDate($date) looks like:
function getall_dbParticipantEntry_byDate($date) {
connect();
$query = 'SELECT * FROM dbParticipantEntry WHERE date = "'.$date.'"';
$result = mysql_query ($query);
$theParticipantEntry = array();
while ($result_row = mysql_fetch_assoc($result)) {
$theParticipantEntry = new ParticipantEntry($result_row['date'], $result_row['id'], $result_row['call_time'],
$result_row['result'], $result_row['notes']);
$theParticipantEntries[] = $theParticipantEntry->get_id();
}
mysql_close();
return $theParticipantEntries;
}
However, while both of these functions work fine individually, when they're both on the same webpage (like I meant them to be), only the one that comes first runs. I tested this by switching them in and out. They both complete their designated tasks, but only when alone on the page.
How can I get them both to run and populate their respective fields?
Thanks so much.
Try the following order:
Connect to mySQL server
Do task 1
Do task 2
Close Connection
For me it looks, like you have closed the mysqlconnection, before you do task2.
Edit:
Maybe you can do it like that?
function f1 ()
{
$res = mysql_connect(...);
// .. do some queries ..
mysql_query($sql, $res);
mysql_close($res )
}
function f2 ()
{
$res = mysql_connect(...);
// .. do some queries ..
mysql_query($sql, $res);
mysql_close($res )
}
Edit:
From php.net:
Be careful when using multiple links to connect to same database (with same username). Unless you specify explicitly in mysql_connect() to create a new link, it will return an already open link. If that would be closed by mysql_close(), it will also (obviously) close the other connection, since the link is the same.
Had lot of trouble figuring it out, since in <=4.3.6 there was a bug which didn't close the connection, but after the patch to >=4.3.7, all my application broke down because of a single script that did this.
You run them both on the same connection. You need to store the resource id returned from mysql_connect and pass this to each mysql method (each uses it's own relevant resource).
that said, I think it is time to:
Move to something more modern like Mysqli or PDO extensions. Much better API
Use some kind of abstraction on the connection managment, preferably one instance of a DB managment class per connection. Plenty of examples on the web, and it is way above the scope of this site to provide such instructions.

Replacing $_HTTP_GET_VARS with $_GET

This is a question about setting up variables in an array for a personal memory aid project analogous to the old paper-based flash cards, which I now want to dust off. A PHP programmer at my old work 5 years ago helped write the page - alas I have long since lost contact, and my PHP skills are rudimentary at best.
Current Code (PHP4)
<?php
# Setting up Variables
reset($HTTP_GET_VARS);
while(list($key,$value) = each($HTTP_GET_VARS))
{
$$key = $value;
}
#set query string, current_id and current_index
$query_string = "sound=$sound&hint=$hint&type=$type";
if(!isset($current_id)) $current_id = "";
if(!isset($current_index)) $current_index = "";
#connect to MySQL
$conn = #mysql_connect( "localhost","xxxx","xxxx" )
or die( "Sorry - could not connect to MySQL" );
#select the specified database
$rs = #mysql_select_db( "xxx", $conn )
or die( "Sorry - could not connect to specified Db" );
# create the query to select the records and then …
Attempts to find solution
Initially I tried a simple substitution as recommended elsewhere. But in the case of this page's code it did not work. I also looked at Replaced $HTTP_GET_VARS with $_GET, but not working and it too did not solve the issue (see below attempt)
Attempted New Code (PHP5)
Assuming a single table Db, with multiple columns, say 'alpha', 'bravo' and 'charlie', then rows of data in the table cells. The now depreciated $HTTP_GET_VARS used to work fine:
<?php
# Setting up Variables
unset($alpha, $bravo, $charlie);
while(list($key,$values) = each($alpha = $_GET['alpha'], $bravo = $_GET['bravo'], $charlie = $_GET['charlie']))
{
$$key = $value;
}
#set query string, current_id and current_index
$query_string = "sound=$sound&hint=$hint&type=$type";
if(!isset($current_id)) $current_id = "";
if(!isset($current_index)) $current_index = "";
#connect to MySQL
$conn = #mysql_connect( "localhost","xxxx","xxxx" )
or die( "Sorry - could not connect to MySQL" );
#select the specified database
$rs = #mysql_select_db( "xxx", $conn )
or die( "Sorry - could not connect to specified Db" );
# create the query to select the records and then...
The error I get with this code is: Notice: Undefined index: alpha in C:\wamp\www\page2.php on line 4
that is not an error, it is a notice - telling you some $_GET array index might not exist where you use it. You might look into php's error_reporting() and possibly set it to error_reporting(E_ERROR) at the very beginngin of the script to avoid notices - in your case that would probably suffice.
http://php.net/manual/en/function.error-reporting.php
4) If you want to have the keys available as local variables and (correctly) have register_globals disabled, what's wrong with extract($_GET);? – DaveRandom
From:
<?php
# Setting up Variables
unset($alpha, $bravo, $charlie);
while(list($key,$values) = each($alpha = $_GET['alpha'], $bravo = $_GET['bravo'], $charlie = $_GET['charlie']))
{
$$key = $value;
}
To:
# Setting up Variables
unset($alpha, $bravo, $charlie);
extract($_GET);
Seems to have done the trick.
Thanks DaveRandom
Because you unset variables that aren't set yet
I think you have in php4 register_globals on and in php 5 off
register_globals is a bad thing so don't put it on

Joomla - Independent SQL query

I'm wondering if someone can give me a bit of a hand.
I'm trying to write a query inside a PHP file in Joomla and its not really working that well, nothing is being output.
I'm very new to this Joomla stuff, so if someone could let me know where I'm going wrong that would be great.
My code is as follows:
$db =& JFactory::getDBO();
$query = "SELECT fullname FROM jos_jxzine_authors WHERE published = '1'";
$db->setQuery($query);
$column = $db->loadResultArray();
echo JHTML::_('select.options', $column, 'value', 'text', $this->categoryMap);
Cheers,
Please use this query
$query = "SELECT fullname FROM `#__jxzine_authors` WHERE published = '1'";
joomla will itself add db prefix. So you must use #_ instead of jos

Categories