Wordpress sql fetch_assoc - sql

I'm having hard time troubleshooting why i cannot seem to run this inside wordpress like on the index.php. It works when its standalone. I created additional table inside wordpress db. Im seeing blank data when i run. Somehow its not picking up the data. I came to know after research i need to use $wpdb and get_results. so I converted it from this old code :
$result = $db->query("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC");
/to wordpress code/
<?php
global $wpdb;
$results = $wpdb->get_results("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC");
?>
//on the header.php
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['name', 'Rating'],
<?php
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "['".$row['name']."', ".$row['rating']."],";
}
}
?>
]);
var options = {
title: 'Figure',
width: 900,
height: 500,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
on the body html i have
<body>
<!-- Display the pie chart -->
<div id="piechart"></div>
</body>

If you are using $wpdb , then you must need to pass 'ARRAY_A' inside get_results like the following to get result in array format.
global $wpdb;
$results = $wpdb->get_results("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC",'ARRAY_A');

Related

Webform : how to count and live display results

Update (that one works)
<?php
if (arg(0) == 'node' && is_numeric(arg(1))) {
$nid = arg(1);
$node = node_load($nid);
if ($node->type == 'webform') {
$count = db_result(db_query('SELECT count(*) FROM {webform_submissions} WHERE nid = %d', $nid));
$atelier_1 = "sources" ;
$sql = "SELECT count(*) FROM {webform_submitted_data} WHERE data LIKE \"".$atelier_1."\" ;";
$count_atel_1 = db_result(db_query($sql));
}
}
echo $sql;
echo $count_atel_1;
?>
This webform has been submitted <?php print $count ?> times.
We'd like to use a webform so that our students should register on some workshops.
The webform works great. Now we'd like to display live the number of students that are already register in on of the workshops so that the other should know if there remains some possibilities of registration (each workshop can only accept 20 students at the same time)
I'm trying with that that doesn't work ($atelier_1 = "sources" ;) is the name of one workshop :
<?php
if (arg(0) == 'node' && is_numeric(arg(1))) {
$nid = arg(1);
$node = node_load($nid);
if ($node->type == 'webform') {
$count = db_result(db_query('SELECT count(*) FROM {webform_submissions} WHERE nid = %d', $nid));
$atelier_1 = "sources" ;
$count_atel_1 = db_result(db_query('SELECT count(*) FROM {webform_submitted_data} WHERE data LIKE %d', $atelier_1');
}
}
echo $count_atel_1;
?>
Any help or suggestion welcome
The only way you can show that live, is by creating an ajax in drupal, or with drupal behaviours, or with javascript.

INSERT in the query part of BigQuery, using google-api-php-client

I wanted to insert thousands of records in the database using INSERT command in php script , as it will easier to access, but https://developers.google.com/bigquery/docs/query-reference , this doesn't show the INSERT command that can be used while querying in php , like ,
$quert->setQuery("Insert into ... values...") , Have tried this in the Query Table of BigQuery web console, but it doesn't seem to work , Is there anyway to use setQuery() with some other command, to insert data ?
BigQuery doesn't support the INSERT command. You would need to create a load job. See https://developers.google.com/bigquery/docs/import#localimport for more information.
In addition to Jordan's answer, here's a snippet of code that should get you started using the Google BigQuery API and the Google API PHP client library for loading your own data into BigQuery programmatically. Note, this snippet simply spits out the raw API response of the load job, including the job Id to the screen - you'll have to add your own polling logic to check on the load job status.
(We will be adding additional documentation about loading your own data, as well as more PHP samples soon).
<?php
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_BigqueryService.php";
session_start();
$client = new Google_Client();
// Visit https://code.google.com/apis/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setScopes(array('https://www.googleapis.com/auth/bigquery'));
$client->setClientId('XXXXXXXXX.apps.googleusercontent.com');
$client->setClientSecret('XXXXXXXXX');
$client->setRedirectUri('http://YOURAPPLICATION/index.php');
// Instantiate a new BigQuery Client
$bigqueryService = new Google_BigqueryService($client);
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
?>
<!doctype html>
<html>
<head>
<title>BigQuery API Sample</title>
</head>
<body>
<div id='container'>
<div id='top'><h1>BigQuery API Sample</h1></div>
<div id='main'>
<?php
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
// Your project number, from the developers.google.com/console project you created
// when signing up for BigQuery
$project_number = 'XXXXXXXXXXXXXX';
// Information about the destination table
$destination_table = new Google_TableReference();
$destination_table->setProjectId($project_number);
$destination_table->setDatasetId('php_test');
$destination_table->setTableId('my_new_table');
// Information about the schema for your new table
$schema_fields = array();
$schema_fields[0] = new Google_TableFieldSchema();
$schema_fields[0]->setName('first');
$schema_fields[0]->setType('string');
$schema_fields[1] = new Google_TableFieldSchema();
$schema_fields[1]->setName('last');
$schema_fields[1]->setType('string');
$destination_table_schema = new Google_TableSchema();
$destination_table_schema->setFields($schema_fields);
// Set the load configuration, including source file(s) and schema
$load_configuration = new Google_JobConfigurationLoad();
$load_configuration->setSourceUris(array('gs://YOUR_GOOGLE_CLOUD_STORAGE_BUCKET/file.csv'));
$load_configuration->setDestinationTable($destination_table);
$load_configuration->setSchema($destination_table_schema);
$job_configuration = new Google_JobConfiguration();
$job_configuration->setLoad($load_configuration);
$load_job = new Google_Job();
$load_job->setKind('load');
$load_job->setConfiguration($job_configuration);
$jobs = $bigqueryService->jobs;
$response = $jobs->insert($project_number, $load_job);
echo '<pre>';
print_r($response);
echo '</pre>';
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Authorize Access to the BigQuery API</a>";
}
?>
</div>
</div>
</body>
</html>

Does session upload progress work with nginx and php-fpm?

I'm running nginx 1.2.3 / php-fpm 5.4.6 and trying to use the Session upload progress feature. During an upload $_SESSION never contains any upload data whatsoever. At first I assumed coding errors, but even the most simple/basic upload progress tests failed to produce anything within $_SESSION.
I now suspect that the file is being POSTed directly to nginx, which completely handles the upload from beginning to end, THEN nginx passes the upload on to php-fpm so quickly that there is no real "progress" to report. Am I correct in this assessment? If so, how can I get around this?
phpconfig confirms that the session.upload settings are all set correctly.
Below is the current test code, borrowed from this blog.
<?php
/* File upload progress in PHP 5.4 */
/* needs a 5.4+ version */
$version = explode( '.', phpversion() );
if ( ($version[0] * 10000 + $version[1] * 100 + $version[2]) < 50400 )
die( 'PHP 5.4.0 or higher is required' );
if ( !intval(ini_get('session.upload_progress.enabled')) )
die( 'session.upload_progress.enabled is not enabled' );
session_start();
if ( isset( $_GET['progress'] ) ) {
$progress_key = strtolower(ini_get("session.upload_progress.prefix").'demo');
if ( !isset( $_SESSION[$progress_key] ) ) exit( "uploading..." );
$upload_progress = $_SESSION[$progress_key];
/* get percentage */
$progress = round( ($upload_progress['bytes_processed'] / $upload_progress['content_length']) * 100, 2 );
exit( "Upload progress: $progress%" );
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<?php if ( isset($_GET['iframe']) ): /* thank you Webkit... */ ?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="demo">
<input type="file" name="uploaded_file">
<input type="submit" value="Upload">
</form>
<script type="text/javascript">
window.location.hash = ""; /* reset */
jQuery("form").bind("submit", function() { window.location.hash = "uploading"; });
</script>
<?php else: ?>
<iframe src="?iframe" id="upload_form"></iframe>
<script type="text/javascript">
jQuery(document).ready(init);
function init() {
/* start listening on submit */
update_file_upload_progress();
}
function update_file_upload_progress() {
if ( window.frames.upload_form.location.hash != "#uploading" ) {
setTimeout( update_file_upload_progress, 100 ); /* has upload started yet? */
return;
}
$.get( /* lather */
"?progress",
function(data) {
/* rinse */
jQuery("#file_upload_progress").html(data);
/* repeat */
setTimeout( update_file_upload_progress, 500 );
}
).error(function(jqXHR, error) { alert(error); });
}
</script>
<div id="file_upload_progress"></div>
<?php endif; ?>
A note in the documentation page on php.net says :
s.zarges 19-Jun-2012 09:32
Note, this feature doesn't work, when your webserver is runnig PHP via FastCGI. There will be no progress informations in the session array.
Unfortunately PHP gets the data only after the upload is completed and can't show any progress.

Get Drop Down Menu, PHP SQL HTML

I am a student and also working in my university. I am not studying computer science.
I mainly do support stuff, but now I should take care of our internship database.
Task: Create a drop down menu from a town which a student choses, then show all internships in this town.
I have an existing SQL database, can create a drop down menu from it, but have NO idea how I can use the selected value. A submit button would be fine, any solution which works is fine.
How can I put the chosen value from drop down menu to a PHP variable?
<?php
$dbanfrage = "SELECT DISTINCT Stadt FROM $tabelle WHERE Land = 'China' OR Land = 'Taiwan' OR Land = 'VR China' ORDER BY STADT ";
$result = mysql_db_query ($dbname, $dbanfrage, $dbverbindung);
if (!$result)
{
$message = 'Ungültige Abfrage: ' . mysql_error() . "\n";
$message .= 'Gesamte Abfrage: ' . $dbanfrage;
die($message);
}
echo "<select>";
echo "<option>Stadt auswählen</option>"; // printing the list box select command
while($nt = mysql_fetch_array($result)) //Array or records stored in $nt
{
echo "<option value = $nt[id]>$nt[Stadt]</option>"; /* Option values are added by looping through the array */
}
echo "</select>"; // Closing of list box
mysql_close ($dbverbindung);
?>
Just suggesting how you can do it --
<select name="country" id="country" onChange="showState();" >
<option value="">Select Country</option>
<option value="1">India</option>
<option value="2">Nepal</option>
</select>
Your Script--
<script type="text/javascript">
function showState( )
{
var value = document.getElementById('country').value;
var url = '<?php echo base_url ?>showstate.php';
$.ajax({
type: "GET",
url: url,
data:{'country':value},
success:function(results)
{
$('#div_state').html(results);
}
});
}
</script>
Your showstate.php php page --
//INCLUDE CONNECTION file to for db query
$type = $_GET['country'];
//Your DB QUERIES
This will load the content in your #div_state div. You can also use Jquery For this..i think this will help you :) an d let me know if you have any query.
<select name="name">
<option value="select">select</option>
<?php
$dbanfragee=mysql_query("SELECT DISTINCT Stadt FROM $tabelle WHERE Land = 'China' OR Land = 'Taiwan' OR Land = 'VR China' ORDER BY STADT ");
while($row=mysql_fetch_array($$dbanfrage)){?>
<option value="<?=$row['id']?>"><?=$row['stadt']?></option>
<?php }?>
</select>

Best way to display current logged-on user in default.ctp?

I am in the process of customizing the default.ctp file and I am trying to display the currently logged on user's name on the top of the page.
In app_controller.php, I have the following:
function beforeFilter()
{
$user = $this->Auth->user();
if($user != null)
{
$this->Session->write('user_name',$user['User']['username']);
}
}
And in default.ctp, I have:
$user = $this->Session->read('Auth.User');
if(!empty($user))
{
echo 'Hello, ' . $user['user_name'];
}
However, it seems like the value $user_name is not getting set anywhere.
What am I doing wrong? Is there a better way to accomplish this?
Update: I've modified it as described in the answer, but it still doesn't work. I get an error:
Undefined index: user_name [APP/views/layouts/default.ctp, line 21]
you can also use the SessionHelper directly in the view / layout
$user = $this->Session->read('Auth.User');
if(!empty($user)) {
echo 'Hi ', $user['user_name'];
}
Cakephp 2.x:
<?php if (AuthComponent::user('id')): ?>
<p class="navbar-text pull-right">
Logged in as <?= AuthComponent::user('name') ?>
</p>
<?php endif; ?>
$user = $this->Session->read('Auth.User');
if(count($user))
echo $user['name'];