I'm new to virtuemart.
While trying to add hits to virtuemart products
I create new filed in "jjws5_virtuemart_products" in database and called it views.
Then I added my PHP code to the place I need it to appear in.
templates/mytemplate/html/com_virtuemart/productdetails/default.php:
<?php //views hits
mysql_query("UPDATE jjws5_virtuemart_products SET views=views+1 WHERE virtuemart_product_id = '$virtuemart_product_id'");
$views_hits = mysql_query("SELECT views FROM jjws5_virtuemart_products WHERE virtuemart_product_id = '$virtuemart_product_id'");
while($total_views = mysql_fetch_array($$views_hits)){
echo "Hits: ".$total_views['views'];
}
?>
However, it's not showing anything.
What should I do to show it?
You use a variable variable to fetch result (maybe only a typo).
Change:
while($total_views = mysql_fetch_array($$views_hits))
in:
while($total_views = mysql_fetch_array($views_hits))
And, in the future, remember to activate error checking in our php code:
error_reporting( E_ALL );
ini_set( 'display_error', 1 );
With error checking, our original code produce this error:
PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in (...)
Related
I'm using Wordpress and I'm performing a query which gives me back this error:
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
My query looks like:
global $wpdb;
$session_uid = isset($_POST["session_uid"]) ? trim(strip_tags($_POST["session_uid"])) : "";
$the_data = isset($_POST["the_data"]) ? trim(strip_tags($_POST["the_data"])) : "";
$ss = "select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id";
$check_last_conversation = $wpdb->get_results($ss);
$response = print $check_last_conversation;
I'm probably missing or misunderstanding something but if I comment out $check_last_conversation and I print something like "Hello", the error goes away.
This is ok:
global $wpdb;
$session_uid = isset($_POST["session_uid"]) ? trim(strip_tags($_POST["session_uid"])) : "";
$the_data = isset($_POST["the_data"]) ? trim(strip_tags($_POST["the_data"])) : "";
//$ss = "select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id";
//$check_last_conversation = $wpdb->get_results($ss);
$response = print 'hello';
So I suppose there is some problems on how I've written my query.
$ss = "select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id";
Said that, I can't see the error.
My apache_error.log and mysql_error_log.err don't report anything
about.
My tables are empty at now but should they print nothing than produce that error.
Can you please suggest something?
EDIT
I see this error in my console
MySQL table empty
My Wordpress Debug is active like:
My debug.log file (wp-content) is not showing any error in my code.
I've discovered that there is a fatal error in the same file of my query:
PHP Fatal error: Call to undefined function get_bloginfo()
I could check it trough the server php error log. Working on MAMP you can find it here:
MAMP/logs/php_error.log
In my case, Wordpress didn't report it in wp-content/debug.log. So you know. It takes me to the conclusion that my file.php doesn't recognise wordpress hooks and could happen for $wpdb too, throughout my query.
As OP mentioned that he is working on external wordpress script and is not able to access his wordpress functionality. To ensure that you retain your wordpress functionality on your external files, please put the following code, at the start of your external script page.
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
The above lines, will include all the wordpress functionality for your script. $path variable stores the path of your wordpress installation folder.
During the development always turn on the error reporting to be aware of warnings notice or fatal errors which can occur very easily if you forget something or miss place something. So better to be aware or errors and turn the error reporting on to see the errors and when in production do disable the error reporting.
go into wp-config.php file and search for : define('WP_DEBUG',false); and change it to define('WP_DEBUG',true);
Even if your query is okay , you will still result to an error , which you will be getting due to incorrect printing of an array:
function get_results of $wpdb , is an function that will return an array as result of multi rows , and for dumping it use :
print_r($check_last_conversation);
or
var_dump($check_last_conversation);
print 'hello; works because it is a string , and $check_last_conversation is an array. Don't wrap the print_r or var_dump or print or echo inside an variable. as they are supposed to print the data inside from variables.
so in case you have more errors , you can look at the errors , by turning the error reporting on.
Sort of going on from Ajit's answer. I was also having issues similar to this that was caused by character collation which was fixed by adding one extra line.
At the top of any php external file that used wpdb I was using the following:
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
You can then use the $charset_collate in your sql statement, e.g.
$sql = "CREATE TABLE `{$wpdb->base_prefix}my_nice_table` (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
) $charset_collate;";
Hope that helps!
So, I've been having a bit of trouble getting MySQL to work.
My Apache server is up and running, PHP is properly installed, and my MySQL server status is running.
When I call phpinfo() it tells me where the mysql.sock is located, both the folder and file exist.
I'm running OSX 10.8.4
I'm following this tutorial to try to get a grasp of how chats would work: http://www.ibm.com/developerworks/library/x-ioschat/
So when I run my php script, the page loads with errors. I'm new to PHP, and am having a difficult time debugging, installation was particularly troublesome.
So if I keep content-type: text/xml uncommented I get this error:
error on line 2 at column 1: Document is empty
It also tells me that the page is rendered up to the first error, so it makes sense that the page is blank when I load it.
When it is commented, the errors begin to make a bit more sense; however, given my absolute newbish nature to PHP I'm not really sure how to navigate them.
Here are the errors:
Notice: Undefined index: past in /messages.php on line 6
-- This makes sense, I think. I haven't built the client side yet, so there should be no past variable provided.
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in /messages.php on line 16
--So, my background is client side, so what this tells me is that my $result variable has a boolean stored in it, instead of whatever is supposed to be in it for the mysql_fetch_assoc() function call. Since the else statement should trigger, that means that either mysql_query() is not working how properly, or my parameter for it is incorrect. I don't know which (if either), nor do I know the solution to either.
Warning: mysql_free_result() expects parameter 1 to be resource,
boolean given in /messages.php on line 24
--Again, same as above; semi-makes sense, very unsure how to go about fixing it.
So, after the errors, nothing is displayed below. Which makes sense because the conditions are written under the assumption they'll have a resource in it, not a boolean (I think??)
In my php file, if you compare it with the tutorial you'll see I took out the htmlentities() calls because I read on StackOverflow that they are not needed, and they didn't change the state of the errors I was getting either way.
Anyway, thanks so much for any advice/help given!
Here is my code so far:
chat.sql:
DROP TABLE IF EXISTS chatitems;
CREATE TABLE chatitems (
id BIGINT NOT NULL PRIMARY KEY auto_increment,
added TIMESTAMP NOT NULL,
user VARCHAR(64) NOT NULL,
message VARCHAR(255) NOT NULL
);
messages.php:
<?php
ini_set('display_errors','1');
//header( 'Content-type: text/xml' );
mysql_connect( 'localhost:/private/var/mysql/mysql.sock', 'root', '' );
mysql_select_db( 'http://localhost/Documents/JoistChat/chat.sql' );
if ( $_REQUEST['past'] ) {
$result = mysql_query('SELECT * FROM chatitems WHERE id > '.
mysql_real_escape_string( $_REQUEST['past'] ).
' ORDER BY added LIMIT 50');
} else {
$result = mysql_query('SELECT * FROM chatitems ORDER BY added LIMIT 50' );
}
?>
<chat>
<?php
while ($row = mysql_fetch_assoc($result)) {
?>
<message added="<?php echo( $row['added'] ) ?>" id="<?php echo( $row['id'] ) ?>">
<user><?php echo( $row['user'] ) ?></user>
<text><?php echo( $row['message'])?></text>
</message>
<?php
}
mysql_free_result($result);
?>
</chat>
test.html:
<html>
<head>
<title>Chat Message Test Form</title>
</head>
<body>
<form action="http://localhost/JoistChat/messages.php"
method="POST">
User: <input name="user" /><br />
Message: <input name="message" /><br />
<input type="submit" />
</form>
</body>
</html>
$past = '';
if ( !empty($_REQUEST['past']) ) {
$past = 'WHERE id > '.intval($_REQUEST['past']);
}
$sql = 'SELECT * FROM chatitems $past ORDER BY added LIMIT 50'
$result = mysql_query($sql) or trigger_error(mysql_error()." [$sql]");
You need to learn basic coding culture. Basic guidelines are
Do no repeat yourself. You are writing all the stuff twice
Always check for error
Do not stack too much code in one line. Make your code distinct, step by step. Need a program to create an SQL query? Okay. get the product of this code in a variable and pass it over. Do not fold all the program in a single line.
Format your SQL properly
This way you'll always know the reason of the problem and have your code run smooth and easier to maintain.
Also just noted that your way of selecting a database is quite a... strange. 'chat.sql' is a file with table creation code, not database. You have to create a database first, then create a table in it, then select newly created database.
As you have been told already, mysql ext is obsoleted. You have to use use PDO instead, as it's the only choice for PHP users whose only idea of database interaction is direct calls to API.
First, create a file with connection options, pdo.php
<?php
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);
Then make your code this way
<?php
ini_set('display_errors','1');
//header( 'Content-type: text/xml' );
include 'pdo.php';
$past = '';
$bind = array();
if ( !empty($_REQUEST['past']) ) {
$past = 'WHERE id > ?';
$bind = array($_REQUEST['past']);
}
$sql = 'SELECT * FROM chatitems $past ORDER BY added LIMIT 50'
$stm = $pdo->prepare($sql);
$stm->execute($bind);
$data = $stm->fetchAll();
?>
<chat>
<?php foreach ($data as $row) { ?>
Since the 'past' index is not set, the boolean condition in the if-statement evaluates to false. As a result the else part is executed.
Your error messages tell you that the query
SELECT * FROM chatitems ORDER BY added LIMIT 50
resulted in a SQL error. Try running that query in your MySql client directly to see what the error is. My guess is that the table/database you are accessing is not created/selected.
I have an admission form which is getting value from database table. Scenario is I have list of courses a student select a course and I pass course ID in URL then use this code to get corresponding Course name in the field: (The form is designed in joomla using breezing forms.)
$this->execPieceByName('ff_InitLib');
$course_id= JRequest::getVar('CID');
global $database, $rec;
$database->setQuery("SELECT * FROM course_list WHERE record = '$course_id' AND name = 'CourseName'");
$row = $database->loadObjectList();
$rec = $row[0];
ff_setValue('ProsCourse', $rec->value);
Unfortunately I get this error:
* EXCEPTION CAUGHT BY FACILEFORMS *
PHP error level : E_NOTICE
PHP filename : /home/web10385/public_html/**/components/com_breezingforms/facileforms.process.php(1219) : eval()'d code
PHP linenumber : 7
Last known pos : Before form custom piece code at line 1
Error message : Undefined offset: 0
* EXCEPTION CAUGHT BY FACILEFORMS *
PHP error level : E_NOTICE
PHP filename : /home/web10385/public_html/**/components/com_breezingforms/facileforms.process.php(1219) : eval()'d code
PHP linenumber : 8
Last known pos : Before form custom piece code at line 1
Error message : Trying to get property of non-object
The above code is the before form piece.
Thanks
You are not constructing the database object....
You have declared $database but you haven't initialized it with an object...That's the problem..It seems you have forgotten it.
Since, before initializing it, it's a non-object type. And you have tried to use it two times, hence you got two errors.
global $database, $rec;
^^ uninitialized....
$database->setQuery("SELECT * FROM course_list WHERE record = '$course_id' AND
^^ but you are using it here....
$row = $database->loadObjectList(.....
^^ here....
From the information seen this is what may be the solution:
EDIT:
$database=JFactory::getDbo();
Here's what I have done:
In Form pieces > Before form add this script:
$this->execPieceByName('ff_InitLib');
$course_id= JRequest::getVar('CID');
//intialize BF utilities
$this->execPieceByName('ff_InitUtilities');
global $database, $rec;
$database = ff_select('SELECT * FROM course_list WHERE record = '.$course_id.' ');
$rec = $database[0];
Then add this to the VALUE field of the TEXT field (course name):
<?php global $rec; return $rec->name; ?>
That should do it.
Peace.
I have created a query that loops through a group of table ID's to get a sum of their combined values. with error handling i get a "Table 'asterisk.custom_' doesn't exist" error and the query is killed obviously. but if i remove the error handling then i get an "mysql_fetch_array() expects parameter 1 to be resource" and the query completes as it should.
Thank in advance for your help.
include("currentday.php");
//---used for testing passing variables
//echo $customID[0];
//echo "<br>".$numrows;
$i = 0;
while($i<=$numrows)
{
mysql_select_db("asterisk") or die(mysql_error()); //This line determines the database to use
$query = "SELECT
vicidial_users.user,
vicidial_users.full_name,
sum(vicidial_agent_log.pause_sec) as sumPause,
sum(custom_$customID[$i].d_amt) as sumDamnt,
sum(custom_$customID[$i].up_amt) as sumUpamnt,
sum(custom_$customID[$i].md_amt) as sumMdamnt,
sum(custom_$customID[$i].s_amount) as sumSamnt,
sum(vicidial_agent_log.dispo_sec)
FROM
vicidial_agent_log
INNER JOIN
vicidial_users
ON
(vicidial_agent_log.user = vicidial_users.user)
INNER JOIN
custom_$customID[$i]
ON
(vicidial_agent_log.lead_id = custom_$customID[$i].lead_id)
WHERE
vicidial_users.user = 'tcx'
GROUP BY
vicidial_users.full_name
ORDER BY
vicidial_agent_log.event_time DESC
";
$queryResult = mysql_query($query);// or die(mysql_error());
while ($rowResult = mysql_fetch_array($queryResult))
{
$pauseResult[] = $rowResult["sumPause"];
$sumdamntResult[] = $rowResult["sumDamnt"];
$sumupamntResult[] = $rowResult["sumUpamnt"];
$summdamntResult[] = $rowResult["sumMdamnt"];
$sumsamntResult[] = $rowResult["sumSamnt"];
}
//print_r($pauseResult);
//echo $pauseResult[0];
$i++;
}
Update:
The table exist in the database:
custom_2346579543413
custom_5466546513564
they are created by the dialer software and im calling them from another query that provides me the numeric part of the table name so this query loops through the values in customID array to make the query, Thanks again
Update:
Sammitch, thank you for the suggestion, however they did not work.
Solution:
Thanks Marc, you confirmed a suspicion i had in that it was looping correctly but for some reason it was looping more times that there we keys. so i echoed $i to confirm and in fact it was it was outputting 0,1,2,3 and since i know there is only 3 keys the last one didn't return anything and so error handling caught it and killed the entire loop and why it appeared correct when error handling was turned off. The solution was actually rather simple and it was in the while loop evaluation string i had used
while($i<=$numrows)
while($i<$numrows)//this worked, the equals part of that gave it an extra loop
and the query completes as it should.
No, it doesn't. "mysql_fetch_array() expects parameter 1 to be resource" means "the query failed, and you didn't bother to check before calling mysql_fetch_array()".
Your problem is that variable expansion inside of a string doesn't like array indexes. You need to change:
"sum(custom_$customID[$i].d_amt) as sumDamnt,"
To:
"sum(custom_{$customID[$i]}.d_amt) as sumDamnt,"
Or:
"sum(custom_" . $customID[$i] . ".d_amt) as sumDamnt,"
For it to work properly.
Can't figure this one out:
$try1 = mysql_query("UPDATE com_users SET `choice_one` = 'president'");
$try2 = mysql_query("UPDATE com_users SET `choice_two` = 'president'");
echo mysql_error($try1);
echo mysql_error($try2);
That PHP code echoes nothing and properly changes choice_two, while not changing choice_one.
$try2 = mysql_query("UPDATE com_users SET `choice_two` = 'president'");
$try1 = mysql_query("UPDATE com_users SET `choice_one` = 'president'");
echo mysql_error($try1);
echo mysql_error($try2);
That PHP code echoes nothing and properly changes choice_one, while not changing choice_two.
How is it possible that the order of these update commands could cause one not to work at all?
The order of the queries will not matter. If there is additional code you are not showing, please post it...
mysql_error()'s first parameter is not the result resource, but rather the connection resource. So to get the first's error, you need to call it immediately after the first query.
$try1 = mysql_query("UPDATE com_users SET `choice_one` = 'president'");
// Call with no parameter right after the query it relates to.
echo mysql_error();
$try2 = mysql_query("UPDATE com_users SET `choice_two` = 'president'");
echo mysql_error();
Note that you are not using a WHERE clause, all rows will be updated the first time. The second time you try running those queries (unless you have reset your data), there will be no rows needing updating and the query will have no effect (mysql_affected_rows() == 0).