phonegap/msql(i) can't establish connection to database - mysql

i'm currently developing an web app for iOS but the app can't get the connection right.
when i'm trying to log in, i get the following iOS popup: index.html Error.
while the PHP files are online,
here some of my code:
connection.php
<?php //Make connection with database
// Verbinden met MySQL Database
$host = "localhost"; // Welke server : localhost
$username = "*******"; // Gebruikersnaam
$password = "****"; // Wachtwoord
$dbnaam = "*****"; // Naam van de database
$db_error1 = "<p>FOUT: verbinden met databaseserver is mislukt</p>"; // Foutmelding 1
$db_error2 = "<p>FOUT: selecteren van database is mislukt</p>"; // Foutmelding 2
$db_error3 = "<p>FOUT: sluiten van database is mislukt</p>"; // Foutmelding 3
// Verbinden met Databaseserver
$con=mysqli_connect($host, $username, $password, $dbnaam);// or die($db_error1);
// verbinden met de database
//mysql_select_db($dbnaam, $db) or die($db_error2);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
demo.js
// define the URL of the server component
//var url ="http://www.jorisgraaumans.nl/dutchmobile/";
//var url = "http://localhost:8888/Mobile/Festival/";
var url = "http://www.rikvandoorn.com/mobile/";
// afvangen van het standaard submit event
// zie ook: http://api.jquery.com/submit/
$('#login').on('pageinit', function(event) {
$('#loginForm').submit(function() {
$.ajax({
type: "POST",
url: "processLogin.php",
cache: "false",
dataType: "json",
data: {
email : $('#email').val(),
wachtwoord : $('#wachtwoord').val(),
},
success: function(phpData){
$("#return").data("login", phpData.login);
console.log("login is: "+ phpData.login);
if(phpData['error'] == true){
$.mobile.changePage("#return", {
transition : "fade"
})
} else {
$.mobile.changePage("#home", {
transition : "fade"
})
}
},
error: function(){
alert('Error');
}
});
return false; // return false to prevent the default submit of the form to the server.
});
// end: pageinit loginForm
});
$('#return').on('pageshow', function(event) {
$("#error_message_log").empty();
$("#error_message_log").prepend('<p>' + $(this).data('login') + '</p>');
});
processLogin.php
<?php //process login form
include 'http://www.rikvandoorn.nl/mobile/connect.php'; //connection to database
if(empty($_POST['email']) || empty($_POST['wachtwoord'])){
$return['error'] = true; //return error
$return['login'] = 'Niet alle velden zijn ingevuld';
} else {
$email = $_POST['email'];
$wachtwoord = $_POST['wachtwoord'];
//Check if user exists
$sql = "SELECT * FROM gebruiker WHERE email = '$email'";
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows == 0){
$return['error'] = true;
$return['login'] = 'Gebruiker bestaat niet';
} else {
//Check if password is correct for user
$sql_2 = "SELECT * FROM gebruiker WHERE email = '$email' && wachtwoord = '$wachtwoord'";
$query_2 = mysql_query($sql_2);
$num_rows_2 = mysql_num_rows($query_2);
if($num_rows_2 == 0){
$return['error'] = true;
$return['login'] = 'Wachtwoord onjuist';
} else {
$return['error'] = false;
$return['login']['email'] = $email;
$return['login']['wachtwoord'] = $wachtwoord;
}
}
}
echo json_encode($return);

Unless you've riddled the code with typos, you're mixing two entirely seperate mysql libraries:
$con=mysqli_connect($host, $username, $password, $dbnaam);// or die($db_error1);
^---note the presence of an 'i'
and in the other scripts:
$result = mysql_query($sql) or die(mysql_error());
^---note the LACK of an 'i'
mysql and mysqli are NOT interchangeable, and connections established in one are utterly useless for the other.
The mysql (WITHOUT an i) library is obsolete and deprecated. Stick with mysqli (WITH an i) only.

Related

Ajax - Inserting values from textarea into database

Hello all on my quest to learn more about ajax I tried making a textarea, in this a text is submitted and then sended to the database, I also made a button to display everything from the database and this works. However when submitted clicking the display all button it just gives this value [object HTMLTextAreaElement] Here is my code:
Select Code/Display
ToDo: <textarea width='200px' height='300px' id='todo'></textarea>
<p id='dbinfo'>Info goes here</p>
<button id='btn'> Send </button>
<button id='request'> Request </button>
<script>
document.getElementById('btn').onclick = function()
{
var dbinfo = document.getElementById('todo').value;
alert(todo); //Here it gives a object htmlcollection ?
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
alert(xmlhttp.readyState + " | " + xmlhttp.status);
var text = xmlhttp.responseText;
alert(text);
document.getElementById('dbinfo').innerHTML = text;
}
xmlhttp.open("POST", "linktodata", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("todo=" +todo);
}
document.getElementById("request").onclick = function()
{
alert("event works");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var result = xmlhttp.responseText;
alert(result);
document.getElementById("dbinfo").innerHTML = result;
}
}
xmlhttp.open("POST", "linktorequest", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
Data Code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "blok-1-am1a";
try
{
if (isset($_POST['todo']))
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("INSERT INTO `database` (`id`, `item`) VALUES (NULL, :item)");
$statement->bindParam(':item', $_POST['todo']);
$statement->execute();
}
}
catch(PDOException $e)
{
echo "Error occured : ".$e->getMessage();
}
echo "Success";
?>
Request code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "blok-1-am1a";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT * FROM `database` ");
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['item']."<br>";
}
}
catch(PDOException $e)
{
echo "Error occured: ".$e->getMessage();
}
echo $data;
?>
So yeah whatever I do the request code works but when submitting I always get [object HTMLTextAreaElement]
Silly me, this is a very simple fix, I made the mistake to use the same var as my <p> tag so the fix is litteraly changing that into todo and everything works.
ToDo: <textarea width='200px' height='300px' id='todo'></textarea>
<p id='dbinfo'>Info goes here</p>
<button id='btn'> Send </button>
<button id='request'> Request </button>
<script>
document.getElementById('btn').onclick = function()
{
var todo = document.getElementById('todo').value; //This needed to be changed into todo
}

PHP MySQL Data To AngularJS

I am using this code to pull data from a MySQL.
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var icon = data[1];
var english = data[2];
var british = data[3];
$('#output').html("<b>id: </b>"+id+"<b> icon: </b>"+icon+"<b> english: </b>"+english+"<b> british: </b>"+british); //Set output element html
}
And it outputs this correctly but my questions is how would put this data into the below.
$scope.items = [
{
english: '<First Row english>',
british: '<First Row british>',
image: '<First Row icon>'
},
{
english: '<Second Row english>',
british: '<Second Row british>',
image: '<Second Row icon>'
}
//So on and so forth for all the records in the DB.
]
This is from api.php not sure if this needs to be returned a certain way?
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
echo $json_response = json_encode($arr);
?>
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
$arr[];
while($obj = mysql_fetch_object($query)) {
array_push($arr, $obj);
}
echo $json_response = json_encode($arr);
?>
JS
$http.get('api.php').success(function(data) {
$scope.items = data;
});

comparing json submitted array and sql returned array and printing difference in text file

I am submitting a javascript array to another php page via ajax which runs a query and returns another array. Then i would like to compare these two arrays and print the difference in a text file. The code give below is creating a text file with no data in it.
Here is the code
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = '[';
values+=valueSelected+",";
for ($i=3;$i<row;$i++)
{
var dv="selectcity"+$i;
var dv1=document.getElementById(dv).value;
var sl="street"+$i;
var sl1=document.getElementById(sl).value;
var po="building"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values+=''+concat+',';
}
values = values.substring(0,values.length-1);
values += ']';
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: {data: values} ,
success: function(){
alert("Success!")
}
});
the value sent to the get_buildings.php is
[newyork::roosevelt st,springfieldevergreen terraceno42,quahogspooner streetno43]
Php code get_buildings.php:-
$a1='newyork::roosevelt st';
$sl= explode("::",$a1);
$a=$sl[1];
$connection_buildings= mysqli_connect('localhost', 'xxxx', 'xxxx', 'DETAILS') or die ('Cannot connect to db');
$sql_query_3 = "select buildings from $a";
$result_query_3=mysqli_query($connection_buildings,$sql_query_3) or die ("check it");
$options=array();
while ($row = $result_query_3->fetch_assoc())
{
$name = $row['buildings'];
$val=$a.$sl[0].$name;
array_push($options,$val);
}
$result = array_diff($_POST['data'], $options);
$fp = fopen("textfile.txt", "w");
fwrite($fp, $result);
fclose($fp);
mysqli_close($connection_buildings);

Ajax GET content from php page

Hi I have a table which I am trying to update with a call to a MySQL database in a separate php page. This separate page loops through a result set and builds the table through a series of echos. In the main page I am trying to insert that echoed content into a div.
This is all kicked off by the user selecting an option from a drop down box.
This is the separate php page. (It works fine when i manually type in the GET parameters, it is the link between the two pages which doesn't seem to work)
tableGetter.php
<?PHP
$user_name = "rocketeermus_pr";
$password = "zuluhead2";
$database = "rocketeermus_pr";
$server = "pdb1.awardspace.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
echo "Bonjour";
if (isset($_GET['composer'])){
echo "Helloooo";
if ($db_found) {
echo "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$SQL = "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
echo "<table class=\"sortable\" id=\"moder\" width=\"800\">";
echo "<th>TITLE</th><th>COMPOSER</th><th>VOICING</th><th>PRICE</th><th></th></tr>";
while ( $db_field = mysql_fetch_assoc($result) ) {
echo "Hi.";
echo "<tr><td>{$db_field['Title']}</td><td>{$db_field['Composer']}</td><td>{$db_field['Voicing']}</td><td>";
echo money_format("%n", $db_field['Price']);
echo "</td><td> <div class=\"product\"> <input value=\"{$db_field['Title']}\" class=\"product-title\" type=\"hidden\"> <input value=\"0.5\" class=\"product-weight\" type=\"hidden\"> <input value=\"{$db_field['NoVox']}\" class=\"googlecart-quantity\" type=\"hidden\"> <input value=\"{$db_field['Price']}\" class=\"product-price\" type=\"hidden\"> <div title=\"Add to cart\" role=\"button\" tabindex=\"0\" class=\"googlecart-add-button\"> </div> </div> </td></tr>";
}
echo "</table>";
mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
?>
And here is the important stuff from the main page:
Javascript:
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
var queryString1 = "";
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
// only if http status is "OK"
if (req.status == 200)
{
var new1 = document.getElementById('composer').value;
queryString1 = "?composer=" + encodeURIComponent(new1);
console.log (queryString1);
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}
function getXMLHTTP() {
var xmlhttp;
if(window.XMLHttpRequest){ //For Firefox, Mozilla, Opera, and Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){ //For ie
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
html:
<div id="menus">
<table>
<tr>
<td><form action=""">
<select name="composer" id ="composer" onchange="getdata();">
<?php
$user_name = "***";
$password = "****";
$database = "****";
$server = "****.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT DISTINCT Composer FROM catalogue ORDER BY Composer";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
while ( $db_field = mysql_fetch_assoc($result) ) {
?>
<option id="composer" onchange="getdata();" value="<?php echo $db_field['Composer'];?>">
<?php
echo $db_field['Composer'];
?>
</option>
<?php
}
}
?>
</select>
</form></td>
</tr>
</table>
</div>
<div id="table">
<?php include("tableGetter.php"); ?>
</div>
The html on the main page works fine, the drop down menu fills up nicely with all the distinct composer names in the database. When an option in the menu is selected the only thing echoed in the "table" div is "Bonjour". It's not getting further than if (isset($_GET['composer'])) in the tableGetter.php page. I'm printing out the queryString1 variable (The get parameters) which is requested in the getData() function and it reports: ?composer=Animuccia%2C%20Paulo which works perfectly when loading the page manually. It just won't work dynamically!
Anybody know what's going on here?
You aren't setting queryString1 before sending the AJAX request. Try this rewrite of getdata().
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
var new1 = document.getElementById('composer').value;
var queryString1 = "?composer=" + encodeURIComponent(new1);
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}

No data from the database after the files downloaded

I want to display the data on a particular condition of the table after the user enters the data you want to display.
But always failed to display the data. I am confused where the fault lies.
It looks like the variable $thn = $ _POST['thn'], $bln = $ _POST['bln'], $periode = $ _POST['periode'] is empty.
please help.
I have four files.
Here the codes:
1.absen_xls.php:
<?php
include '../../inc/inc.koneksi.php';
ini_set('display_errors', 1); ini_set('error_reporting', E_ERROR);
include '../../excel/PHPExcel.php';
include '../../excel/PHPExcel/IOFactory.php';
$table = 'absen_karyawan';
$bln = $_POST['bln']; //this not work, I don't know why?
$thn = $_POST['thn']; //this not work, I don't know why?
$periode = $_POST['periode']; //this not work, I don't know why?
$where = "WHERE tahun = '$thn' AND bulan = '$bln' AND periode = '$periode'";
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$sql = "SELECT namakaryawan,tahun,bulan,periode,absen FROM $table $where";
$query = mysql_query($sql);
// bold
$objPHPExcel->getActiveSheet()->getStyle("A2:C2")->applyFromArray(array("font" => array( "bold" => true)));
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A2', 'No')
->setCellValue('B2', 'Nama')
->setCellValue('C2', 'Kehadiran');
$baris = 3;
$no = 0;
while($row=mysql_fetch_array($query)){
$no = $no +1;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue("A$baris", $no)
->setCellValue("B$baris", $row['namakaryawan'])
->setCellValue("C$baris", $row['absen']);
$baris = $baris + 1;
}
//border
$border = $baris - 1;
$styleArray = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
$objPHPExcel->getActiveSheet()->getStyle('A2:C'.$border)->applyFromArray($styleArray);
unset($styleArray);
//width
$objPHPExcel->getActiveSheet()->getColumnDimension("A")->setWidth(5);
$objPHPExcel->getActiveSheet()->getColumnDimension("B")->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension("C")->setWidth(15);
//align center
$objPHPExcel->getActiveSheet()->getStyle('A2:C'.$border)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Absen');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excelformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="absen.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>
2.ajax.php:
// JavaScript Document
$(document).ready(function(){
$(function(){
$('button').hover(
function() { $(this).addClass('ui-state-hover'); },
function() { $(this).removeClass('ui-state-hover'); }
);
});
$("#tampil_data").load('modul/lap-absen/tampil_data.php');
$("#print").click(function(){
var thn = $("#thn").val();
var bln = $("#bln").val();
var periode = $("#periode").val();
cetakabsen(thn,bln,periode);
});
function cetakabsen(c1,c2,c3){
var thn = c1;
var bln = c2;
var periode = c3;
$.ajax({
type : "POST",
url : "modul/lap-absen/absen_xls.php",
data : "thn="+thn+"&bln="+bln+"&periode="+periode,
success : function(data){
window.open('http://localhost/gudang/modul/lap-absen/absen_xls.php');
}
});
}
});
Change your function to this one:
function cetakabsen(c1,c2,c3){
var thn = c1;
var bln = c2;
var periode = c3;
var data = "thn="+thn+"&bln="+bln+"&periode="+periode;
window.open('http://localhost/gudang/modul/lap-absen/absen_xls.php?'+data);
}
And receive your values like this in absen_xls.php:
$bln = mysql_real_escape_string($_GET['bln']);
$thn = mysql_real_escape_string($_GET['thn']);
$periode = mysql_real_escape_string($_GET['periode']);
PS: Go for mysqli or PDO, dont use the mysql extension.