Query a database with drupal 7 - database

I have searched the internet for a way to use our history database on our drupal 7 site. I have a database built with names, marriage dates, etc. I would like to have a basic page to do a search. I found a site that helped with the code, but it is not working. I am not a programmer, but I can follow directions. Here is the code I have:
On a basic page using php code as my input format,
<html>
<body>
<script language=”javascript” type=”text/javascript”>
<!–
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try{
ajaxRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e){
// Something went wrong
alert(“Your browser broke!”);
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxDiv");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var lastphp = document.getElementById("lastphp").value;
var queryString = “?lastphp=” + lastphp;
ajaxRequest.open(“GET”, “/php/check.php” + queryString, true);
ajaxRequest.send(null);
}
//–>
</script>
<form name="myForm">
<table border=”0″>
<tr>
<td width = 100>Last Name: <br /></td>
<td><input type="text" id="lastphp"> </td>
</tr>
</table>
<br />
<input type="button" onclick="ajaxFunction()" value="Search" />
</form>
<div id="ajaxDiv"></div>
</body>
</html>
Then, I created a php file:
<?php
//Connect to MySQL Server
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("localhost","root","") or die('Cannot connect to the database because: ' . mysql_error());
//specify database ** EDIT REQUIRED HERE **
mysql_select_db(“genealogy”) or die(“Unable to select database”); //select which database we’re using
// Retrieve data from Query String
$last = $_GET['lastphp'];
// Escape User Input to help prevent SQL Injection
$last = mysql_real_escape_string($last);
//Build and run a SQL Query on our MySQL tutorial
$query = “SELECT * from columbus_ledger_enquirer_obituary_db”; //just grab every row from our table
$results = mysql_query($query)or die(mysql_error());
//print what the user entered (eventually I’m sure you’ll want to use this data in your query)
echo “You Entered: ” . $last . “<br><br>”;
//print the results
echo “Database Results: <br>”;
while($row = mysql_fetch_array($results)){
echo “$row[lastname]<br>”; //NOTE: Here we are printing all the data from the ‘lastname’ column of our database, either change this name, or make sure you have a lastname column with some data in it
}
?>
I placed the php file in a folder called php under /sites/default.
The basic page has a nice box and search button, but when I type in a name, nothing happens.
Can anyone here tell me what's wrong?
Thanks

As #SpaceBeers mentions this is really not a good way to do this kind of thing in Drupal (Google "bootstrapping Drupal" or "access custom database in Drupal" for some ideas).
The reason your code probably isn't working, though, is because you're calling your AJAX in using the following code:
ajaxRequest.open(“GET”, “/php/check.php” + queryString, true);
The problem is in the path...you mention you've put your "php" folder in '/sites/all', so surely the path from your AJAX call needs to be the same:
ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString, true);

These days "there is a module for it" (to query external databases in formats such as Oracle, MS SQL, Postgress, SQLite, or just any PDO compliant format). It's the Forena module (disclosure: I'm a co-maintainer of it).
Head over to its demo site to see it as work, and refer to its community docu for way more details. Here is a quote from its docu:
... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

Related

angularjs state.go doesn't reload php file

I have a code which uses ui-router. It is navigating in 2 files(state). 1 is the php file which displays all the contents of an SQL db, while the other is an HTML file retrieving data from 1 row of the SQL db.
The php file is getting the contents of the db using
$inbox = mysql_query("SELECT * FROM wps LIMIT $offset,$limit");
$rows = mysql_num_rows($inbox);
while($row = mysql_fetch_assoc($inbox)){
$id = $row['id'];
$RDate = $row['RDate'];
echo '<tr class="border_bottom">';
echo '<td>'.$id.'</td>';
echo '<td>'.$RDate.'</td>';
echo '</tr>';
The html file is accessed by an ng-click which transfers the user in to this state and is getting the details of the SQL db row using $http.post method from a js file.
After editing the row of the SQL DB by using the HTML file, I will have to go back to the php file using $state.go. But after returning to the php file, the changes are still not reflecting.
I already tried using
$state.go('phpstate',{}, {reload:'phpstate'});
to refresh the rows displayed but it doesn't really work.
Please check the below code
$state.go($state.current, {}, {reload: true});
Reload option parametr is boolean. Maybe you must try it:
$state.go('phpstate',{}, {reload:true});

Why is data not received from node server to angular client?

I've the following SETUP: AngularJS for UI, MongoDB for database and Node.js for server.
FUNCTIONALITY of my web page: It is tabular website and 3 tabs to enter details all of which is saved to Database and one tab called EDIT/DOWNLOAD to display specific details like 4-5 columns(fields) of each row(document) and further, for each document displayed there is an option to edit or download details.
WORK FLOW: on click of tab EDIT/DOWNLOAD a function [ say viewDatabaseDetails()] is called which in turns gets those details to be displayed as a table for each document in database.
On click of download button again that specific document detail goes to NODE and then calls the specific document and save it all according to a template text file and send that file for download to client and deletes that file.
On click of edit button, it again picks up data and populate those 3 tabs where user has to enter but here any changes made is updated in database instead of saving as a new document.
ISSUE: : When I click on function viewDatabaseDetails(), sometimes Angular displays data, sometimes it fails. Success of receiving data to display varies between 1-4 clicks on tab button to call viewDatabaseDetails(). Also, when I click on download button, sometimes files is received for download on the first click, sometimes after clicking on download button for 2-4 times file is received by client. I have checked node part on console, angular is sending all the details correctly every single time I click on download button or viewDatabaseDetails(), node is doing all the processing like data operations, creating file to send, creating proper response to send all the documents details but somehow it is not being received by angular.
What might be happening is either the data is lost in network or timeout happens before receiving data/file as only server to client communication has issue. I checked network console in IE [i've a restriction to use only IE] upon success time taken is greater than time taken upon failure.
EDIT:
Error explained according to below code: When I click on view button in UI, sometimes data is displayed correctly, sometimes I get error as SyntaxError: Invalid Character.
UI:
<button ng-click="viewDatabase()"> View </button>
Controller:
$scope.viewDatabase = function(){
$http.get('/getDatabase').success(function(response){
$scope.outputs = response;
}).error(function(){
console.log("error");
});
};
UI: for displaying response
<div>
<table>
<tr>
<td>Name </td>
<td>City </td>
<td>Country </td>
</tr>
<tr ng-repeat="output in outputs">
<td>{{output.Name}} </td>
<td>{{output.City}} </td>
<td>{{output.Country}} </td>
</tr>
</table>
</div>
Node and MongoDB code:
//other require statements
var mongoose = require('mongoose');
var db = mongoose.connect(ConnectionString:port);
var PropertyFileSchema = new Schema({
Name: String,
City: String,
Country: String
});
PropertyFile = db.model('PropertyFile', PropertyFileSchema');
http.createServer(function(req,res){
//putting only required part of code
if(req.url=="/getDatabase"){
res.writeHead(200,{'content-type': 'application/json'});
PropertyFile({},'Name City Country', function(err, docs){
console.log(docs); //always displays if anything in database
res.end(JSON.stringify(docs));
});
}
});

passing user to the browser in meanjs

I'm reading source code of meanjs project to learn javascript and MEAN better. There is an expression:
<!--Embedding The User Object-->
<script type="text/javascript">
var user = {{ user | json | safe }};
</script>
I understand that it is sending the user record as a json object to the browser, but can't find 'safe' filter on google. Could anyone please point me to the right direction or explain what this is?
Yes, the user object is actually getting passed to the browser, and it actually displays in the source code. In practice, my deployed app has this in the source code (actual data generalized):
<!--Embedding The User Object-->
<script type="text/javascript">
var user = {"_id":"123abc456xyzetc","displayName":"First Last","provider":"local","username":"newguy","__v":0,"roles":["admin"],"email":"my#email.com","lastName":"Last","firstName":"First"};
</script>
As you can see, it actually dumps user information into the source code, which isn't the most secure way to develop an app. If you comment out or remove the line in your layout.server.view.html file (var user = {{ user | json | safe }};), then you can't really log in. It logs you in, then immediately kicks you out.
You'll notice, though, in your config > passport.js file that some information is removed before being passed back to the browser, starting at around line 14:
// Deserialize sessions
passport.deserializeUser(function(id, done) {
User.findOne({
_id: id
// The following line is removing sensitive data. In theory, you could remove other data using this same line.
}, '-salt -password -updated -created', function(err, user) {
done(err, user);
});
});
If you do decide to remove additional fields, though, be aware that this can break your app. I removed the user id, for example, and most of my app worked, but it broke some specific functions (I believe it was Articles, if I remember right).

Show Filtered Lookup in CRM2011 from Silverlight Grid

I recently show up all products on a "Lookup" Field on a Inline Silverlight App on the CRM2011 Quote form.
I do this with directly calling the link of the Lookup:
var uri = (ScriptObject)crmUri.Invoke("create", string.Format("/_controls/lookup/lookupinfo.aspx?LookupStyle=single&objecttypes={0}", objectType));
var dArgs = (ScriptObject)HtmlPage.Window.CreateInstance("Object");
dArgs.SetProperty("items", new string[] { "" });
dynamic dlgResult = HtmlPage.Window.Invoke("showModalDialog", uri, dArgs, "dialogWidth:500px;dialogHeight:700px");
Our Customer wants to filter the lookup view on a value of a specific field on the product form.
This field is a optionset and can be 1 or 2.
I tried to add "&$filter=" + "producttypecode/Value" + " eq 1" or "&$filter=" + "producttypecode" + " eq 1" in the link, but this always Returns a error message.
Are there any suggestions?
This is a valid request that I just tested.
ProductSet?$filter=ProductTypeCode/Value eq 1
If that doesn't work I'd recommend the following troubleshooting steps.
Test your full URL in a browser first.
If it works in a browser then fire up fiddler and see what the difference is between the silverlight request and your manual request using a browser.
If you are having difficulty determining the correct full url I'd recommend downloading and becoming familiar with the CRM OData Query Designer. It will allow you to use a GUI to generate your request strings, and test them out. It can be found here.
http://crm2011odatatool.codeplex.com/
We solved this issue by adding a new System View and call it from its URL.

Creating an AJAX Searchable Database

Currently I am using MySQLi to parse a CSV file into a Database, that step has been accomplished. However, My next step would be to make this Database searchable and automatically updated via jQuery.ajax().
Some people suggest that I print out the Database in another page and access it externally.
I'm quite new to jquery + ajax so if anyone could point me in the right direction that would be greatly appreciated.
I understand that the documentation on ajax should be enough to tell me what I'm looking for but it appears to talk only about retrieving data from an external file, what about from a mysql database?
The code so far stands:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
</head>
<body>
<input type="text" id="search" name="search" />
<input type="submit" value="submit">
<?php
show_source(__FILE__);
error_reporting(E_ALL);ini_set('display_errors', '1');
$category = NULL;
$mc = new Memcache;
$mc->addServer('localhost','11211');
$sql = new mysqli('localhost', 'user', 'pword', 'db');
$cache = $mc->get("updated_DB");
$query = 'SELECT cat,name,web,kw FROM infoDB WHERE cat LIKE ? OR name LIKE ? OR web LIKE ? OR kw LIKE ?';
$results = $sql->prepare($query);
$results->bind_param('ssss', $query, $query, $query, $query);
$results->execute();
$results->store_result();
?>
</body>
</html>
I understand that the documentation on ajax should be enough to tell me what I'm looking for but it appears to talk only about retrieving data from an external file, what about from a mysql database?
Close. It fetches data from a URI. You need to provide a URI that the data can be requested from (so you need a server side script to get the data from the database and expose it over HTTP — you can't talk directly to the database from the browser).
You have got your data already, so you just need to write views for it.
Usually, people will write an HTML view first so they can build on something that works.
Then you just need to write an alternative view that generates data in a fashion that is easy to parse with JavaScript. JSON is popular, and PHP comes with facilities for generating JSON output.
jQuery will set an X-Requested-By header that you can use to choose between returning HTML or JSON output.

Resources