use Ionic framework with php files - php

I'm creating a mobile app with the Ionic Framework. I got all the html pages created online. Now i want some backend code to get data from a sql server. Receiving the data is no problem with php. But when I use php pages I don't have the interface I created with Ionic.
How can I use php pages (instead of html) and still get the lay out from ionic? Example: my scorebord.php
<?php
$servername = "localhost:3306";
$username = "ssss";
$password = "dffd";
$dbname = "ddddd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT user_username,user_city,user_highscore FROM tbl_user";
$result = $conn->query($sql);
?>
<ion-view style="" title="Scorebord">
<ion-content class="has-header" overflow-scroll="true" padding="true" style="background: url(img/hX1ml1TVGgABo3ENE6Qg_menu3.png) no-repeat center;">
<h1 style="">Scorebord</h1>
<table style="width:100%">
<?php
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row["user_username"] ?></td>
</tr>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
</table>
</ion-content>
</ion-view>
btw: Is it safe to just configure my database in a php file like that? Anyone a good alternative?

The Mobile App will be saved on a device which probably can't interpret PHP code, unlike a web server.
If you dont know/want javascipt then an iframe is probably your only option.
example.com/table.php
<h1 style="">Scorebord</h1>
<table style="width:100%">
<?php
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {?>
<tr> <td><?php echo $row["user_username"] ?></td></tr>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
</table>
your app
<ion-view style="" title="Scorebord">
<ion-content class="has-header" overflow-scroll="true" padding="true" style="background: url(img/hX1ml1TVGgABo3ENE6Qg_menu3.png) no-repeat center;">
<iframe src="example.com/table.php"/>
</ion-content>
</ion-view>
But a better solution is to use JavaScript to make http requests for JSON data or full html templates(like table.php).
I would use a json backend
highscores.php
<?php
$servername = "localhost:3306";
$username = "ssss";
$password = "dffd";
$dbname = "ddddd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT user_username,user_city,user_highscore FROM tbl_user";
$result = $conn->query($sql);
$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json);
your app
angular.module('ionicApp', [])
.controller('MainCtrl', function($scope, $http) {
$http.get('http://example.com/highscores.php').then(function(resp) {
$scope.users = resp.data;
}, function(err) {
console.error('ERR', err);
})
});
<html ng-app="ionicApp">
<body ng-controller="MainCtrl">
<ion-content>
<ion-list>
<ion-item ng-repeat="user in users">
{{user.user_username}}
</ion-item>
</ion-list>
</ion-content>
</body>
</html>

Related

Deleting data from database using PHP

I am trying to delete data from MySQL using PHP
<?php
if (isset($_POST['delete'])) {
$queryDelete = "Delete FROM info WHERE userID={$_POST['delete']}";
if (!($database = mysqli_connect("localhost", "root", ""))) {
die("Could not connect to database. </body></html>");
}
if (!mysqli_select_db($database, "project2")) {
die("Could not open books database. </body></html>");
}
if (!(mysqli_query($database, $queryDelete))) {
echo "<p>Could not execute query!</p>";
die(mysqli_error($database) . "</body></html>");
}
mysqli_close($database);
}
this is my delete.php using it on this page
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Style.css">
</head>
<header>
<div>
<p id="page">Users List</p>
<img id="title_pic" src="images/title_pic.jpg" alt="#">
</div>
</header>
<body>
<?php include 'bar.php' ?>
<?php include 'delete.php' ?>
<br><br><br><br>
<h1 style="color:yellow;"> List of all Users: </h1>
<br>
<?php
$query = "SELECT userID, fName, email FROM info";
if (!($database = mysqli_connect("localhost", "root", ""))) {
die("Could not connect to database. </body></html>");
}
if (!mysqli_select_db($database, "project2")) {
die("Could not open project database. </body></html>");
}
if (!($result = mysqli_query($database, $query))) {
echo "<p>Could not execute query!</p>";
die(mysqli_error($database) . "</body></html>");
}
mysqli_close($database);
while ($row = mysqli_fetch_row($result)) {
foreach ($row as $value) {
echo "<span style='color:white;'> $value </span>";
}
echo ' <form action = "delete.php" method = "POST">';
echo '<input type="submit" name= "delete" value="delete" class="btn">';
echo '</form>';
echo "<br>";
}
?>
</html>
It's redirecting me to delete.php page but when I go back to the second one (Displayuser.php) all info are there and nothing is deleted
I used the same technique to add info but I am having trouble to delete them from the table.
Here is how your code should look like. First in your form, provide the ID of the user you want to delete. Make sure to enable mysqli error reporting and select the right database when connecting.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect("localhost", "root", "", 'project2');
$database->set_charset('utf8mb4'); // always set the charset
$users = $database->query("SELECT userID, fName, email FROM info");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Style.css">
</head>
<body>
<header>
<div>
<p id="page">Users List</p>
<img id="title_pic" src="images/title_pic.jpg" alt="#">
</div>
</header>
<?php include 'bar.php' ?>
<?php include 'delete.php' ?>
<br><br><br><br>
<h1 style="color:yellow;"> List of all Users: </h1>
<br>
<?php
foreach ($users as $user) {
foreach ($user as $value) {
echo "<span style='color:white;'>'.htmlspecialchars($value).'</span>";
}
echo ' <form action = "delete.php" method = "POST">';
echo '<button type="submit" name="delete" value="'.htmlspecialchars($user['userID']).'" class="btn">Delete</button>';
echo '</form>';
echo "<br>";
}
?>
</html>
Then in your delete.php, read the POST value and delete the row with that ID using prepared statement.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect("localhost", "root", "", 'project2');
$database->set_charset('utf8mb4'); // always set the charset
if (isset($_POST['delete'])) {
$stmt = $database->prepare("DELETE FROM info WHERE userID=?");
$stmt->bind_param('s', $_POST['delete']);
$stmt->execute();
}

Hiding a button if table is not empty

I am trying to hide a "add to table" button once ONE (basically, if the table is not empty) input has been added to the table.
I tried using a IF statement but with no luck.
Since i am a begginer in this and need to do this for my homework, i would be very grateful, if you could atleast point me into the right direction.
Regards.
This is my code. I have a script that toggles a contact form trough a button click. I would like that button to dissapear if the table IS NOT empty. So 1 input = button gone. I am only addint the relavant part of the code.
EDIT: FINAL CODE.
<?php
$koncnica=".png";
$conn = mysqli_connect("localhost", "username", "pass", "DB");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT debelina, odkat, rob, vtor, id, narocilo FROM polica where id='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" .
$row["debelina"] ." cm".' ✎'. "</td><td>" .
$row["odkat"].' ✎'. "</td><td>" .
$row["rob"].' <img src ="http://granital.owjej.org/wp-content/uploads/2019/03/' . $row['rob'] . $koncnica.'"height="20px"/>✎'.
"</td></tr>";}
echo "</table>";
}
$conn->close();
?>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#a').click(function() {
$('.b').toggle("slide");
});
});
</script>
<?php if ($result->num_rows == 0) { ?>
<div id="a">Dodaj</div>
<?php } ?>
<?php
$conn->close();
?>
<div class="b" style="display: none;">
<div class="container">
FORM
</div>
</div>
This does the trick :)
<?php if ($result->num_rows == 0) { ?>
<div id="a">Dodaj</div>
<?php } ?>
You can wrap the "button" HTML in some PHP which will cause it only to be rendered if the table has no items in it:
<?php if ($result->num_rows == 0) { ?>
<div id="a">Dodaj</div>
<?php } ?>

How to fetch from MySQL database “Hindi” हिन्दी text (Indian local language)

Database which stores my data is this:
Now I want to fetch that data and display on my php page, but when I'm trying to fetch data in my php code I'm getting text into the following formate
UID= ????/??????????/????/?????/?????/Test upgrade/1
UID= ????/??????????/??????/??????/??????????/159/1
UID= ????/??????????/??????/??????/??????????/190/1
UID= ????/??????????/??????/??????/??????????/194/1
UID= ????/??????????/??????/???????/?????? (??.)/730/1
UID= ????/??????????/??????/???????/?????? (??.)/742/1/1
UID= ????/??????????/??????/???????/?????? (??.)/732/1
UID= ????/??????????/??????/??????/??????/98/8/1
UID= ????/??????????/??????/??????/??????/48/10/1
Referring to this question I have changed my database charset to "utf8_unicode_ci", but Still not working. I have written following code to fetch the data
datebase connection page
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "user";
$dbPassword = "xxxxxxxxxxxxx";
$dbName = "tutorialsssxxxxx";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
and index page
<?php
include $_SERVER['DOCUMENT_ROOT']."/header.php";
?><br>
<!DOCTYPE HTML>
<html lang="hi">
<head>
<title><?php echo $_GET['dta']; ?> Tutorials Mrtutorials.net</title>
<link href='style.css' rel='stylesheet' type='text/css'>
<script src="jquery.min.js"></script>
<script type="text/javascript">
// Show loading overlay when ajax request starts
$( document ).ajaxStart(function() {
$('.loading-overlay').show();
});
// Hide loading overlay when ajax request completes
$( document ).ajaxStop(function() {
$('.loading-overlay').hide();
});
</script>
</head>
<body>
<div class="content">
<div class="dta"> <div class="list_item"><h2><?php echo $_GET['dta']; ?> Tutorials</h2></div>
<div class="post-wrapper">
<div class="loading-overlay"><div class="overlay-content">Loading.....</div></div>
<div id="posts_content">
<?php
//Include pagination class file
include('Pagination.php');
//Include database configuration file
include('dbConfig.php');
$limit = 10;
//get number of rows
$queryNum = $db->query("SELECT COUNT(*) as postNum FROM posts");
$resultNum = $queryNum->fetch_assoc();
$rowCount = $resultNum['postNum'];
//initialize pagination class
$pagConfig = array('baseURL'=>'getData.php', 'totalRows'=>$rowCount, 'perPage'=>$limit, 'contentDiv'=>'posts_content');
$pagination = new Pagination($pagConfig);
//get rows
$query = $db->query("SELECT * FROM posts Where type=$yyy ORDER BY id DESC LIMIT $limit");
if($query->num_rows > 0){ ?>
<div class="posts_list">
<?php
while($row = $query->fetch_assoc()){
$postID = $row['id'];
?>
<table width="" border="0" cellspacing="5" cellpadding="0">
<tr class="up">
<td style="font-size: 45px; padding-left:5px; padding-right:5px"><?php echo $row["id"]; ?></td>
<td valign="left" width="100%"><?php echo $row["title"]; ?> <br> <?=$value['type']?></td>
</tr>
</table>
<?php } ?>
</div>
<?php echo $pagination->createLinks(); ?>
<?php } ?>
</div>
</div></div>
</div>
</body>
</html><?php
include $_SERVER['DOCUMENT_ROOT']."/footer.php";
?>
You need to use "set_charset"
Try this: (in your index.php)
//initialize pagination class
$pagConfig = array('baseURL'=>'getData.php', 'totalRows'=>$rowCount, 'perPage'=>$limit, 'contentDiv'=>'posts_content');
$pagination = new Pagination($pagConfig);
mysqli_set_charset( $db, 'utf8');
//get rows
$query = $db->query("SELECT * FROM posts Where type=$yyy ORDER BY id DESC LIMIT $limit");
To be precise, In your case you need to add this in code where you fetching the db:
mysqli_set_charset( $db, 'utf8');
mysqli_set_charset( $db, 'utf8'); will help you set unicode on the db connection. Now to show it in the page, you will still have to set the character encoding in html.
Remember to do this. Otherwise your page will still not show you the unicode characters.
<head>
<meta charset="UTF-8">
</head>
Nothing worked for me as per reply on stackoverflow.com, to display on web page, the Hindi Text from MySql through PHP.
The following code worked for me. Please write your comments
enter code here
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM audio WHERE AudioFor= 'Aarti' ORDER BY Name";
mysqli_set_charset( $conn, 'utf8'); **// to get the hindi font/text displayed**
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) { ?>
<table cellpadding="10">
<thead>
<tr align= "centre"><h3> Other Aartis </h3></tr>
<tr>
<th>Aarti Of</th>
<th>Wordings</th>
<th>Click to Listen</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td >" . $row["Name"]."</td><td >" . $row["Wording"]. "</td><td >". ' Click To Listen '. '</td></tr>';
}
} //else {
// echo "0 results";
//}
?>
After connecting to SQL Server and Database run the following query
msql_query("SET CHARACTER SET utf8")

Cannot show longblob in an image tag

I have been struggling with this problem for many hours now. The page is supposed to display a list of images from a database stored as longblobs, but all it does is to show me the 'img' icon for each icon. Any suggestions to what I can do?
showImage.php
<?php
include_once('connection.php');
$sql = "SELECT filetype, picture FROM postcards WHERE ID=". $_GET['ID'];
$rows=$conn->query($sql);
foreach ($rows as $row) {
header("Content-type: ". $row["filetype"]);
echo $row["picture"];
}
$conn=null;
?>
listImage.php
<?php include_once('connection.php'); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="uft-8">
<title>List database content</title>
</head>
<body>
<?php
$sql = "SELECT * FROM postcards";
$rows=$conn->query($sql);
foreach ($rows as $row) {
echo '<p>Upload by person: '.$row["title"].'</p>';
echo '<p><img src="showimage2.php?ID='.$row["ID"].'"></p>';
}
$conn=null;
?>
</body>
</html>
connection.php
<?php
$dsn = "mysql:host=localhost;dbname=tellastory";
$username="root";
$password="";
$e="";
try {
$conn = new PDO($dsn, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
};
?>
Thanks in advance!

Running Ajax From HTML list Issues

I am trying to run Ajax on a web application which is suppose to list associated data with HTML List from MySQL database using jQuery and PHP.I have two tables in MySQL database called Item and Items as below:
and I have to PHP file called index.php and result.php as:
================================================================== index.php
<html>
<head></head>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'testdb');
if ($mysqli->connect_errno)
{
die('Unable to connect!');
}
else{
$query = 'SELECT * FROM items';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p>
Select a language
<ul id="item">
<?php
while($row = $result->fetch_assoc()){
?>
<li><div id="selectLanguage"><?php echo $row['item']; ?></div></li>
<?php
}
?>
</ul>
</p>
<p id="result"></p>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectLanguage').click(function()
{
alert("hello");
if($(this).val() == '') return;
$.get(
'results.php',
{ id : $(this).val() },
function(data)
{
$('#result').html(data);
}
);
});
});
</script>
</body>
</html>
and the result.php is
====================================================================== result.php
<?php
$mysqli = new mysqli('localhost', 'root', '', 'testdb');
$resultStr = '';
$query = 'SELECT type FROM item where name='.$_GET['item'];
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
$resultStr.='<ul>';
while($row = $result->fetch_assoc())
{
$resultStr.= '<li><strong>'.$row['id'].'</strong> - '.$row['type'];
'</li>';
}
$resultStr.= '</ul>';
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>
now the first part(index.php) is rendering the list base on the items table but I can't click at the second or third item besides none of them not returning any values to the page.
Can you please let me know what I am doing wrong here?
You're creating the selectLanguage div id multiple times. You should use a class instead of an id. Also. the val() is null. You should use html() instead.
looks like in result.php you're populating the list by parameter 'item'
when in your jquery ajax function you're passing the parameter as 'id'
change one of those and you should be good.
Change Your index.php file as :
<html>
<head></head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'testdb');
if ($mysqli->connect_errno)
{
die('Unable to connect!');
}
else{
$query = 'SELECT * FROM items';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p>
Select a language
<ul id="item">
<?php
while($row = $result->fetch_assoc()){
?>
<li><div id="selectLanguage<?php echo $row['id']; ?>"><?php echo $row['item']; ?></div></li>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectLanguage<?php echo $row['id']; ?>').click(function()
{
//alert("hello");
$.ajax({
type : 'POST',
url : 'result.php',
data: {
id : <?php echo $row['id']; ?>
},
success : function(data){
$('#result').html(data);
}
});
});
});
</script>
<?php
}
?>
</ul>
</p>
<p id="result"></p>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
</body>
</html>

Categories