I am building a simple app with Intel XDK and I need to connect my app to a mysql database. Because the Intel XDK does not allow PHP files I needed to connect my html to php via javascrapt and json.
Here is the PHP code I found and edited which sends an PHP array as JSON object to the Intel XDK app:
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT * FROM quotes LIMIT 1";
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
$jsonData = $row;
}
/* free result set */
mysqli_free_result($result);
//encode to JSON format
echo "<h1>" . json_encode($jsonData) . "</h1>";
}
else {
echo "<h1>" . json_encode($jsonData) . "</h1>";
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
My index.html has the following code:
<head>
<script>
function GetQuote() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://domain/db.php?get_rows=json", false);
xmlhttp.send();
}
</script>
</head>
<body onload="GetQuote()">
<div id="quote"> </div>
</body>
My code is working and my app shows the latest row in my table. The problem is that this code returns the entire row so I get someting like this on my screen:
["column1","column2"]. What I need is "Column1" as a record and "column2" as a record.
Anyone who can help me? I've been working on this problem the entire day and can't find a solution.. Thanks!
This is the code I have now:
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxx", "xxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
I now just get an empty screen with [null,null].. Anyone knows what's wrong with this code? I tried debugging, but I am new to PHP and I can't manage to make it work.. Thanks!
Try something like this
$query = "SELECT column1,column2 FROM quotes LIMIT 1";
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret['name1'] = $row['column1'];
$ret['name2'] = $row['column2'];
// Or you can simply use, comment the above two lines and uncomment the following two lines.
//$ret[] = $row['column1'];
//$ret[] = $row['column2'];
//encode to JSON format
echo json_encode($ret);
If you find any type error here, kindly share
Related
I'm newbie in php and JavaScript, and I want to print all rows in my table
I use this code, it works but no output have come from it, and no errors occurs
function show(){//function get data and send it to Ajax, and I can make 1 function get 3 parameters
// var formData = new FormData();
// formData.append('result', $(("#a").val()));//php elem , html element
// formData.append('contactUsEmail', $("#contactUsEmail").val());
// formData.append('contactUsMessage', $("#contactUsMessage").val());
if(false){
swal("Attention !", "Please fill in all fields", "error");
}else {
//Ajax
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var text =this.responseText; // 0 unvalid , 1 true
// document.getElementById("a").innerHTML = this.responseText;
}
}
ajax.open("GET", "one.php", true);
ajax.send(formData);
}
}
php code here :
<?php
function OpenCon()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "chat";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
return $conn;
}
function show(){
$sql = "SELECT id FROM masseges";
$result = OpenCon()->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: ". $row["id"]."bb";
}
} else {
echo "0 results";
}
OpenCon()->close();
}
No errors in page, but a blank page. How can I fix it ?
You are not actually returning any html tags back to your website.
You should be able to see the result from the php echo in the network tab of your development console.
If you want to fill a table, I suggest you create the table structure on your website and add the data from php as a new table row.
HTML:
<table>
<tr>
<th>id</th>
</tr>
</table>
PHP:
echo "<tr><td>id: ". $row['id']."bb</td></tr>";
Another word of advide:
Have a look at jquery! Gonna save you a a lot of time!
I have been where you are half a year ago :-)
I’m really struggling with this task for my course and hope someone doesn’t mind helping out or just offering guidance here. Basically I’m trying to create a simple Javascript XML Http Request to display basic information (the country_name & country_capital fields) from the database just in the html page. Below I just describe the apparent stages from the guide, and what I have done.
Firstly the ‘database.html’ page contains javascript XHR code which I think is mostly correct, but may have an error. To be honest I’m not 100% sure what else it does other than somehow refer to the getcountries.php file.
Secondly the getcountries.php file is where I’m really struggling as I’ve never coded in PHP. I think it’s supposed to fetch the data from the local server (I’m running XAMPP) and echo the results on the web page.
The database on phpMyAdmin is simple with just a table of countries including a primary key ID number, the country name, capital and currency, with the details below:
Database name = countries_db
Table name = countries_table
Table fields:
country_ID (primary key)
country_name
country_capital
country_currency
An example entry: 2, USA, Washington DC, US Dollar
To summarise, my question is this: how can I edit what I’ve done to correctly fetch the data from the database and display it on the page?
Really appreciate any help or advice here, thanks a lot.
<!-- Code on Page 1 (database.html) -->
<p id="txtHint"></p>
<p id="hint"></p>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // detects whether the browser has XMLHttpRequest functionality
// code for modern browsers
xmlhttp=new XMLHttpRequest(); // creates an XMLHttpRequest object
} else { // code for old browsers
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() { // onreadystatechange defines the function to be called when the readyState property changes
if (this.readyState==4 && this.status==200) {
document.getElementById("hint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getcountries.php?q="+str,true);
xmlhttp.send();
}
</script>
<!-- Code on Page 2 (getcountries.php) -->
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','');
if (!$con) {
die('Could not connect: ' .mysqli_error($con));
}
mysqli_select-db($con,"countries_db");
$sql="SELECT country_name AND country_capital FROM records";
$result = mysqli_query($con,$sql);
echo "Results:"
error_reporting(E_ERROR | E_PARSE);
\
while($row = mysqli_fetch_array($result)) {
echo $row['country_name'] . "<br>";
echo $row['country_capital'] . "<br>";
}
mysqli_close($con);
?>
Assuming that this is the structure of your data base:
Database name = countries_db
Table name = countries_table
Table fields:
country_ID (primary key)
country_name
country_capital
country_currency
The problem is that you have some syntax error in your code change this lines:
mysqli_select-db($con,"countries_db");
$sql="SELECT country_name AND country_capital FROM records";
with:
mysqli_select_db($con,"countries_db");
$sql="SELECT country_name, country_capital FROM countries_table";
Alternative: using PDO:
Try this instead of your getcountries.php implementation
<?php
$driver = 'mysql';
$database = "dbname=countries_db";
$dsn = "$driver:host=localhost;unix_socket=/home/cg/mysql/mysql.sock;$database";
$username = 'root';
$password = 'root';
try {
$conn = new PDO($dsn, $username, $password);
echo "<h2>Database countries_db Connected<h2>";
}catch(PDOException $e){
echo "<h1>" . $e->getMessage() . "</h1>";
}
$sql = 'SELECT country_name, country_capital FROM countries_table';
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "Results:";
echo "<table style='width:100%'>";
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
foreach($row as $value)
{
echo sprintf("<td>%s</td>", $value);
}
echo "</tr>";
}
echo "</table>";
?>
Use mysqli_select_db instead of mysqli_select-db in your getcountries.php:
mysqli_select_db($con,"countries_db");
I need to write a word in database, and i cant couse i get an error that: ReferenceError: Patikrinta is not defined Here is my ajax script which sends data to php file. Bellow there is php script if you need it. Cant find solution in stackowerflow.
$s .= "\n\t<td>";
$canEdit = getPermission('tasks', 'edit', $a['task_id']);
$canViewLog = getPermission('task_log', 'view', $a['task_id']);
$currentTasken=$a['task_id'];
$currentUser=$AppUI->user_id;
$currentPercent="5";
$currentDescription="Patikrinta";
if ($canEdit) {
$s .= ("\n\t\t".'<a href="#">'
. "\n\t\t\t".'<img src="./images/icons/tick.png" alt="' . $AppUI->_('Check')
. '" border="0" width="12" height="12" onclick="javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', '.$currentDescription.')" />' . "\n\t\t</a>");
}
$s .= "\n\t</td>";
?>
<script type="text/javascript">
// Note that you should use `json_encode` to make sure the data is escaped properly.
var currentTasken = <?php echo json_encode($currentTasken=$a['task_id']); ?>;
var currentUser = <?php echo json_encode($currentUser=$AppUI->user_id); ?>;
function insertData(currentTasken, currentUser, currentPercent, currentDescription)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","modules/tasks/datafile.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// Here, use the JS variables but, likewise, make sure they are escaped properly with `encodeURIComponent`
xmlhttp.send("currentUser=" + encodeURIComponent(currentUser) + "¤tTasken=" + encodeURIComponent(currentTasken) + "¤tPercent=" + encodeURIComponent(currentPercent)+ "¤tDescription=" + encodeURIComponent(currentDescription));
}
</script>
Here is my php script:
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$currentPercent = isset($_POST['currentPercent']) ? $_POST['currentPercent'] : '';
$currentDescription = isset($_POST['currentDescription']) ? $_POST['currentDescription'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task, task_log_description) VALUES ('$currentUser' , '$currentTasken', '$currentDescription')" ) ;
if($ins)
{
$check = mysql_query("SELECT * FROM dotp_tasks");
$numrows = mysql_num_rows($check);
if($numrows > 1)
{
//$pass = md5($pass);
$inss = mysql_query("UPDATE dotp_tasks SET task_percent_complete = '$currentPercent' WHERE task_id='$currentTasken'") ;
if($inss)
{
die("Succesfully added Percent!");
}
else
{
die("GERROR");
}
}
else
{
die("Log already exists!");
}
}
else
{
die("ERROR");
}
}
else
{
die("Log already exists!");
}
?>
Have you tried adding quotes around the function arguments which are strings? JS is looking for a reference to 'Patikrinta' because you are not adding quotes around the string. It should be a bit more like this:
javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', \''.$currentDescription.'\')" />' . "\n\t\t</a>");
The other arguments work because they are being passed as numbers and Javascript interprets them as such. The difference here is the value of $currentDescription is Patikrinta which is not a number and so JS looks for a variable or object called that.
As a side note - it's worth switching to use MySQLi if you can. MySQL_* functions are deprecated.
i am trying to change the select query on click or on change of the button,
the table name field names in the table general are equal to the fragment after page = (About, ContactInformation)
i'm not getting any error nor getting any result
index page code
<script>
function selectQuery(str) {
if (str == "") {
document.getElementById("editor").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("editor").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","queries.php?page="+str,true);
xmlhttp.send();
}
}
</script>
<ul>
<li><i class="fa fa-file-text"></i> About us</li>
<li><i class="fa fa-list-alt"></i> Contact us</li>
</ul>
queries.php page
<?php
$page = intval($_GET['page']);
$result = mysql_query("SELECT general.'".$page."' ".
"FROM general") or trigger_error(mysql_error());
echo $result;
?>
i tried to echo $page in the queries.php file directly but also it is not showing, seems its not even getting here,
so can anyone help pls
You aren't fetching those results. You need to use mysql_fetch_* functions to get those rows. Now the next part is whether you would like to get a JSON response or just output an HTML markup that can be used directly.
Here's what the fetching would look like:
<?php
$page = $_GET['page'];
$data = array();
$result = mysql_query("SELECT general.".$page." FROM general") or trigger_error(mysql_error());
while($row = mysql_fetch_assoc($result)) {
// fetch the results
$data[] = $row;
}
echo json_encode($data);
?>
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's a version with mysqli:
<?php
$default_columns = array('About', 'ContactInformation', 'Others', 'Home');
if(isset($_GET['page']) && in_array($_GET['page'], $default_columns)) {
$return_value = array();
$page = $_GET['page'];
$db = new mysqli('localhost', 'username', 'password', 'database');
$sql = "SELECT $page FROM general";
$query = $db->query($sql);
while($row = $query_fetch_assoc()) {
$return_value[] = $row[$page];
}
echo implode(' ', $return_value);
}
?>
So I am using this code:
function updateSelect(a) {
$type = a;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest(); }
else {
xmlhttp=new ActiveXObject
("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","selectbox.php?type=".$type,false);
xmlhttp.send();
selectText=xmlhttp.responseText;
document.getElementById("cultpicklist").options.length=0;
document.getElementById("cultpicklist").innerHTML = selectText;
And for some reason it gives me EVERY option value on the entire page (I have several DISTINCT select boxes)! selectText only pulls from a small subset of the database (i.e. an entirely different table from where this data is coming from) - why would it be doing this?
Here's what is generated on selectbox.php:
<?php
include "mysql_config.php";
$con = mysql_connect($host, $user, $pass);
if (!$con)
{
die('Could not connect to the database, please contact administrator');
}
mysql_select_db($db);
while ($cultrow = mysql_fetch_array($rescult)) {
ECHO '<option name="culture[]" value="'. stripslashes($cultrow['cult_id']) .'">'. stripslashes($cultrow['cult_desc']) .'</option>';
}
?>