SQL/PHP make an array with column name / value for specific unique id - sql

I have an sql table named clients where each client is stored in a row, with a unique (auto increment) id and the column names are: clientname, clientlastname, clientmobile and so on.
I want to make an array that will retrieve the contents of a specific client (row) and will be like : clientname => lalala, clientlasthname=>lalalala... and so on.
Then I want to display the results in an html form (non submitable, just display)
each cell in the form has a unique id and name same as the column names of the sql db.
I just new at it and cant seem to get it.
Here's what I've done so far:
<?php
header("Content-Type:text/html; charset=utf-8");
if ($_POST) {
$link = mysql_connect("localhost","userid","pw");
if (!$link) { die("Database Connection Failed". mysql_error()); }
mysql_set_charset('utf8',$link);
$db_select = mysql_select_db("form2",$link);
if(!$db_select){ die("Database Selection Failed " . mysql_error()); }
} else { echo "Search:"; }
?>
<html>
<head> </head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="css/dsearch.css" />
<link rel="stylesheet" href="css/base.css" />
<link type="text/css" href="css/selected/jquery-ui-1.8.18.custom.css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="js/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="js/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript" src="js/dropdowndata.sql/dropdowndata.clients.js"></script>
<script language="javascript" type="text/javascript" src="js/buttons.js"></script>
<body>
<form class="form" id="dsearch" name="dsearch" action="dsearch.php" method="POST" enctype="application/x-www-form-urlencoded">
<div class="dsearch">
<li class="ui-widget"><label for="clients">client id: </label><input class="client" name="searchcid" style="width:100px" /></li>
<li class="cell3"><input type="submit" value="Αναζήτηση" style="color:green; width:210px; " /></li>
</div>
</form>
<div class="results">
<?php
$result1 = mysql_query("SELECT * FROM clients WHERE id='$_POST[searchcid]'", $link);
if(!$db_select) { die("No Data found in db " . mysql_error()); };
$items=array();
while($row = mysql_fetch_array($result1)){
$items[$row['id']] = $row['dlastname'];
/* here is where I need the help I guess,
I need to fill the $items array with the data formatted as mentioned above.
And after that I want to populate a form that I haven't already written with the
values ,any help or maybe any suggestions on some tutorials I could go study
would be appreciated.
It goes on like this: */
}
print_r ($items);
?>
</div>
</body>
</html>
<?php
if ($_POST) {
mysql_close($link);
}
?>
Edit: figured out how to get the array
$clinfo=array();
$clinfo=mysql_fetch_assoc($result1);
print_r ($clinfo);
Now I need a way to go put the data where the field id equals the id of the docinfo array

figured out how to do it with a little php and jquery,
here it is:
$(document).ready(function(){
<?php
if($_GET){
foreach($docinfo as $key=>$val) {
echo "$('#" . $key . "').val('" . htmlspecialchars($val) ."');";
}
}
?>
});
This creates a jquery line for each cell id and fills it with the appropriate value
Any comments or improvements are extremely appreciated

Related

Button click to display a table from mysql in ibm mobile first

I am in process of learning so kindly help me to do how the retrieval of table from mysql in ibm mobile first by just clicking an button from my html page. I have tried but not working help please
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>vikdemodb</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<!--application UI goes here-->
<div id="header">
<h1>database Demo</h1>
</div>
<div id="wrapper">
<input type="button" id="databasecon" value="click me to get data from db" /><br />
</div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
My main.js
function wlCommonInit(){
$('#databasecon').click(loadSQLRecords);
}
function loadSQLRecords(){
var invocationData = {
adapter : 'vikadap',
procedure : 'getstudinfo',
parameters : []
};
WL.Client.invokeProcedure(invocationData,{
onSuccess : loadSQLQuerySuccess,
onFailure : loadSQLQueryFailure
});
}
function loadSQLQuerySuccess(result){
window.alert("success");
console.log("Retrieve success" + result);
console.log(result.invocationResult.resultSet);
}
function loadSQLQueryFailure(result){
WL.Logger.error("Retrieve failure");
}
You have a button in your HTML:
<input type="button" id="databasecon" value="click me to get data from db" />
You handle this button in wlCommonInit():
$('#databasecon').click(loadSQLRecords);
In loadSQLRecords() you call an adapter procedure to retrieve data from the database. If this operation succeeds then it calls the loadSQLQuerySuccess callback function.
It is this function that you are supposed to handle the display of the response from the backend (your database). But what are you doing? You only print to the console the response. You do not handle at all, displaying it in the application - in the HTML.
So in your HTML, you need to prepare a place holder that you will append the result into. For example: <table id="mytable"></table>
Then you need to populate the table with the data...
So in loadSQLQuerySuccess, you could for example do the following... this is where you need to learn HTML and JavaScript to accomplish what YOU want it to look like:
function loadFeedsSuccess(result) {
if (result.invocationResult.resultSet.length > 0)
displayFeeds(result.invocationResult.resultSet);
else
loadFeedsFailure();
}
function loadFeedsFailure() {
alert ("failure");
}
function displayFeeds(result) {
for (var i = 0; i < result.length; i++) {
$("#mytable").append("<tr><td>" + result[i].firstName + "</td></tr>");
$("#mytable").append("<tr><td>" + result[i].lastName + "</td></tr>");
}
}
Note that you need to create your own code in the for loop to make it look like how you want it to look, and of course append your own properties from the database, instead of "firstName" and "lastName".

Invocation of table from mysql is not working

My adapter works fine but cant able to invoke in client side code. I have created a button and if I click it should display the database table.
Yes I have copied this code from other blog but modified here so need help.
<html>
<head>
<meta charset="UTF-8">
<title>vikdemodb</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<!--application UI goes here-->
<div id="header">
<h1>database demo</h1>
</div>
<div id="wrapper">
<input type="button" id="databasecon" value="click me to get data from db" /><br />
</div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
my main.js
function wlCommonInit(){
$('#databasecon').click(loadSQLRecords);
}
function loadSQLRecords(){
var invocationData = {
adapter : 'vikadap',
procedure : 'getstudinfo',
parameters : []
};
WL.Client.invokeProcedure(invocationData,{
onSuccess : loadSQLQuerySuccess,
onFailure : loadSQLQueryFailure
});
}
function loadSQLQuerySuccess(result){
console.log("Retrieve success" + result);
console.log(result.invocationResult.resultSet);
}
function loadSQLQueryFailure(result){
WL.Logger.error("Retrieve failure");
}
My adapter implementation
var procedure1Statement = WL.Server.createSQLStatement("select * from studentinfo");
function getstudinfo() {
return WL.Server.invokeSQLStatement({
preparedStatement : procedure1Statement,
parameters : []
});
}
here my adap.xml
<wl:adapter name="vikadap"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.ibm.com/mfp/integration"
xmlns:sql="http://www.ibm.com/mfp/integration/sql">
<displayName>vikadap</displayName>
<description>vikadap</description>
<connectivity>
<connectionPolicy xsi:type="sql:SQLConnectionPolicy">
<!-- Example for using a JNDI data source, replace with actual data source name -->
<!-- <dataSourceJNDIName>java:/data-source-jndi-name</dataSourceJNDIName> -->
<!-- Example for using MySQL connector, do not forget to put the MySQL connector library in the project's lib folder -->
<dataSourceDefinition>
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://localhost:***/***</url>
<user>****</user>
<password>****</password>
</dataSourceDefinition>
</connectionPolicy>
</connectivity>
<procedure name="getstudinfo"/>
I must say that this is quite sad. You copy the entire "implementation" from elsewhere, but do not copy the one thing that will finish it - displaying the data that is retrieved by the adapter. Then, you ask a question how to do it... I don't know what is your end goal with your project, but I don't think you'll get there if you will continue like this.
One way you could display the result is a function like this:
function displayFeeds(items){
var ul = $('#itemsList');
for (var i = 0; i < items.length; i++) {
var li = $('<li/>').html(items[i].sid);
li.append($('<li/>').html(items[i].sname));
li.append($('<li/>').html(items[i].sgrade));
li.append($('<hr>'));
ul.append(li);
}
}
This function assumes there is a UL in your HTML, and then appends LI's into it with items.
You will need to change this to fit your table design, as well as change sid, sname and sgrade with the correct property names from your database.
Next time you copy, at least copy everything: http://javatechig.com/ibm-worklight/invoking-adapter-procedure-in-ibm-worklight

MVC 4 : jQuery AutoComplete shows list of "undefined"

I am new with MVC and now have problem. Please give me solution.
I am creating simple AutoComplete textbox in MVC4.
Here is my code
In controler:
public ActionResult List(string term)
{
DebateEntities _db = new DebateEntities ();
var results = from u in _db.Users
where u.username.ToLower().Contains(term.ToLower())
select new { u.username};
return Json(results, JsonRequestBehavior.AllowGet);
}
In View
#model DebateApp.Models.MessageModels
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<link href="http://www.asp.net/ajaxLibrary/jQueryCodeSamplesMVC/Content/redmond/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />
</head>
<body>
#using (Html.BeginForm())
{
<fieldset>
<legend>User Lookup</legend>
#Html.TextBox("name")
#Html.TextBox("userID")
<input type="submit" value="Find" />
</fieldset>
}
</body>
<script src="http://www.asp.net/ajaxLibrary/jQueryCodeSamplesMVC/Scripts/jQueryUI/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="http://www.asp.net/ajaxLibrary/jQueryCodeSamplesMVC/Scripts/jQueryUI/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$("#name").autocomplete({
source: '#Url.Action("List")',
select: function (event, ui) {
$("#name").val(ui.item.username);
}
});
</script>
</html>
When i type the 'd' in textbox, a list appear, but they all "undefined".
When i choose a "undefined" option, it show correct username.
How can i solve "undefined" list ?
Thank you
Yeah even i faced this problem earlier. The main reason for it could be your jquery code couldnt extract contents from source reference tags.
I suggest you to use the following
<script src="code.jquery.com/jquery-1.8.3.js"; type="text/javascript"></script>
<script src="code.jquery.com/ui/1.9.2/jquery-ui.js"; type="text/javascript">
and for jquery something like
<script type="text/javascript">
$(function () {
$('#name').autocomplete({
source: '#Url.Action("List")',
minLength: 1,
select: function (evt, ui) {
}
});
});
</script>
and you can use the same code for the controller. i can find no problem with it. Most probably you wont get the undefined any more.

Assigning a variable from a select box

I have been trying all day to "catch" or assign/bind to the chosen state and assign it to a variable called "text" so that I can use it in yet another API call for the other drop down box "Products".
I figured I must just be missing something and was hoping for a little help.
Thanks.
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<title>Legis Connect</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<link rel="stylesheet" href="css/kendo.common.min.css">
<link rel="stylesheet" href="css/kendo.black.min.css">
<link rel="stylesheet" href="css/kendo.mobile.all.min.css">
<link rel="stylesheet" href="css/kendo.dataviz.min.css">
<script src="js/kendo.all.min.js"></script>
</head>
<body>
<div class="k-widget k-header">
<span class="infoHead">Information</span>
<p>
<input id="state" placeholder="Select State..." />
</p>
<p>
<input id="products"/>
</p>
<script>
$(document).ready(function() {
$("#state").kendoDropDownList({
// optionLabel: "Select State...",
dataTextField: "name",
dataValueField: "abbreviation",
dataSource: {
transport: {
read: {
url: "http://openstates.org/api/v1/metadata/?apikey=????????",
dataType: "jsonp"
}
}
}
});
// change: function(test){
// var text = this.value()
var states=$("#state").data("kendoDropDownList");
states.bind("change", function(e) {
var text = (this.value())
alert (text)
});
$("#products").kendoDropDownList({
optionLabel: "Select product...",
dataTextField: "legislature_name",
dataValueField: "legislature_name",
dataSource: {
transport: {
read: {
url: "http://openstates.org/api/v1/metadata/"+text+"/?apikey=???????????????????",
dataType: "jsonp"
}
}
}
})
$("#products").data("kendoDropDownList");
});
</script>
</div>
</body>
</html>
It appears that you're trying to create cascading dropdowns; when you choose a value in the states dropdown list, it loads the products available for the selected state. There's a helpful article from Telerik on how to do that with the combo box controls (works the same from dropdown lists): http://docs.kendoui.com/getting-started/web/combobox/cascading. There's actually a property called cascadeFrom which you can set on the products dropdown list to tell it to cascade from the states dropdown list. Hope that helps!

Multiple Google map with php loop

I am trying to dispaly multiple maps with a php loop but i cant get it to work here is the code stripped down...
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAA5iXFaQoABBiRl7JNx5HFuxSa5RD4FXABRIVtLveK1-E6gmai7BR1Y63hhzwAO9ZPoNDgLDBQ_Z6B4Q" type="text/javascript"></script>
</head>
<body onload="load()" onunload="GUnload()">
<?php
if($_POST['select'] == "place"){
$posts = $facebook->api("/search?q=".urlencode($_POST['search'])."&type=".urlencode($_POST['select'])."&center=".urlencode($_POST['center'])."&distance=".urlencode($_POST['distance'])."");
//print_r($posts);
$num = "1";
$num2 = "1";
foreach($posts as $v) {
foreach($v as $v2) { ?>
<div>
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map-<?php echo $num++; ?>"));
map.setCenter(new GLatLng(<?php echo $v2['location']['latitude']; ?>, <?php echo $v2['location']['longitude']; ?>), 13);
}
}
//]]>
<div id="map-<?php echo $num2++; ?>" style="width: 500px; height: 300px"></div>
<p><?php echo $v2['location']['latitude']; ?></p>
<p><?php echo $v2['location']['longitude']; ?></p>
</div>
<?php
}
}
}
}
?>
</body>
</html>
I have tried to put the javascript within the loop but this doesnt work.
Has anyone got any suggestions at the moment it will only show the last map within the loop???
Thanks
I can tell you why it doesn't work. You're redefining the same load() function each time through the loop. So when document loads, and load() gets called, it just displays the last map. By the way, you should also be using google map V3 api instead of V2, but that's a different topic.
Something like this should fix this. First, put this in the <head> section:
<script type="text/javascript">
var loaders = [];
function load() {
for (var i = 1; i < loaders.length; i++) {
loaders[i]();
}
}
</script>
Then change your loop to this:
foreach($posts as $v) {
foreach($v as $v2) { ?>
<div>
<script type="text/javascript">
//<![CDATA[
loaders[<?php echo $num; ?>] = function() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map-<?php echo $num++; ?>"));
map.setCenter(new GLatLng(<?php echo $v2['location']['latitude']; ?>, <?php echo $v2['location']['longitude']; ?>), 13);
}
};
//]]>
<div id="map-<?php echo $num2++; ?>" style="width: 500px; height: 300px"></div>
<p><?php echo $v2['location']['latitude']; ?></p>
<p><?php echo $v2['location']['longitude']; ?></p>
</div>
<?php
}
}