How to get data from database by id? - php

I want to get data from "data_show.php?id=2"
my code below (detail1.php)
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
$query = sprintf("SELECT name, humidity, ph, degree FROM dataklm");
$result = $mysqli -> query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$mysqli->close();
print json_encode($data);
i've success retrieve data with above code, but i want select them per id. i just tried like below. but it's not work
$query = sprintf("SELECT name, humidity, ph, degree FROM dataklm WHERE id='$_GET['id']");
i passed data to this
<?php
include 'header.php';
include 'conn.php';
?>
<html>
<style type="text/css">
#chart-container {
width: 1000px;
height: 1000px;
}
</style>
<div class="container">
<div class="jumbotron">
<h1 class="display-3" style="text-align:center;">Smartfish</h1>
<p class="lead" style="text-align:center;">Monitoring System</p>
</div>
</div>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<script src="./assets/chart.js"> </script>
<script src="./app.js"> </script>
</body>
</html>

I didn't find anything that is passing the id from your html page to the php page.
Pass the id from html to php page as:-
view more
Doing this you will be passing an id from url to the next page. and you can get this id by using GET method as
$id = $_GET['id'];
then use your query.
Hope this will help you.

If you write the "$_GET['id']" just like this in the string it's gonna be threated as a string.
$query = sprintf("SELECT name, humidity, ph, degree FROM dataklm WHERE id='".$_GET['id']."'");

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();
}

combine jquery in php for displaying a collapsible list fetched from database

The following program is supposed to display the subjects and subcategory in collapsible list order.
But the collapsible list is applied for the first entry only. The rest of the items appear static. They dont collapse. Why??????????
<html><head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<?php
$con = mysqli_connect("localhost","root","","test");
$sql="select * from subject";
$res_subject=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($res_subject))
{
?>
<UL id="subj_tree">
<LI><span> <?php echo $row['sub_name'];?> </span>
<UL>
<?php
$sql="select * from sub_categry where sub_id=".$row['sub_id'];
$res_sub_cat=mysqli_query($con,$sql);
while($val=mysqli_fetch_array($res_sub_cat))
{
?> <LI><span> <?php echo $val['sub_cat_name']; ?> </span></LI>
<?php } ?>
</UL>
</LI>
</UL>
<?php
}
?>
</html>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(function(){
$('#subj_tree').find('UL').hide();
$('#subj_tree').find('SPAN').click(function(e){
$(this).parent().children('UL').toggle();
});
});
mysql db is like as follow:
sub_categry: sub_cat_id, sub_cat_type, sub_id (foreign key subject.sub_id)
subject: sub_id, sub_name.
The jQuery find() method only gives you the first element that matches the selector. If you want all the tags under #subj_tree to be hidden, you would have to use
$('#subj_tree ul').hide();
You can't trigger a click using find() function. You should use this function instead:
$('#subj_tree > li > span').click(function() {
$(this).parent().children('UL').toggle();
});
It's because your structure is completely wrong. Your code is also wildly inefficient. Also, you are including jquery twice. That probably doesn't do much good!
Your script tag also isn't closed and it should be included within the body.(something you are also missing)
Can you try it like this?:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<style>#subj_tree ul {display: none;}</style>
</head>
<body>
<?php
$con = mysqli_connect("localhost", "root", "", "test");
$sql = "select * from subject";
$res_subject = mysqli_query($con, $sql);
while( $row = mysqli_fetch_array($res_subject) ) {
?>
<ul id="subj_tree">
<li><span> <?php echo $row['sub_name']; ?> </span>
<ul>
<?php
$sql = "select * from sub_categry where sub_id=" . $row['sub_id'];
$res_sub_cat = mysqli_query($con, $sql);
while( $val = mysqli_fetch_array($res_sub_cat) ) {
?>
<li><span> <?php echo $val['sub_cat_name']; ?> </span></li>
<?php } ?>
</ul>
</li>
</ul>
<?php
}
?>
<script type="text/javascript">
$(function () {
$('#subj_tree > li span').on("click", function (e) {
var parent = $(this).parent();
$('ul', parent).toggle();
});
});
</script>
</body>
</html>
see this JSFiddle for a working example;
https://jsfiddle.net/qum571nn/

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")

How to delete MySql database row with PHP button

I have an backend website setup that displays all the users on my site in an organised table, I should be able to edit and delete the users from the php page. However I cannot get the delete function to work, here is the code.
Data_Display.php
<?php
include('session.php');
?>
<?php include ("db.php"); ?>
<?php
$sql = "SELECT * FROM username ORDER BY UserNameID DESC";
$query = mysql_query($sql) or die(mysql_error());
if (isset($_GET['UserNameID'])) {
$id = mysql_real_escape_string($_GET['UserNameID']);
$sql_delete = "DELETE FROM users WHERE id = '{$UserNameID}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/ico" href="favicon.ico">
<title>Network TV - All Records</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body >
<div class="container">
<div class="content">
<h1>Network TV Users and User control panel</h1>
<br>
<div class="toolbar">
Add New Person
Home
</div>
<br>
</div>
</div>
<div class="container">
<div class="content">
<?php if (mysql_num_rows($query)) { ?>
<?php while ($rows = mysql_fetch_assoc($query)) { ?>
<div class="separator"></div>
<h2><b>User reference:</b> <?php echo $rows['UserNameID']; ?></h2>
<h2><b>Name:</b><?php echo $rows['name']; ?></h2>
<h2><b>Email address:</b> <?php echo $rows['email']; ?></h2>
<h2><b>Gender:</b> <?php echo $rows['sex']; ?></h2>
<h2><b>Profile Picture:</b> <?php echo $rows['imagelink']; ?></h2>
<div class="toolbar">
Edit
Delete
</div>
<?php } /* End Loop */ ?>
<div class="separator"></div>
<?php } else { ?>
<div class="separator"></div>
<h2>There are no records to display</h2>
<div class="separator"></div>
<?php } /* End Rows Checking */?>
</div>
</div>
<div class="container">
<br>
<br>
<br>
<br>
<br>
</div>
<script>
function confirmDelete ( message, url )
{
var confirmation = confirm ( message );
if ( confirmation == true ) {
window.location = url;
} else {
return false;
}
}
</script>
</body>
</html>
Session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "Oliver");
// Selecting Database
$db = mysql_select_db("users", $connection);
if(!isset($_SESSION)){session_start();}
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from username where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: home.php'); // Redirecting To Home Page
}
?>
db.php
<?php
$connection = mysql_connect('localhost', 'root', 'Oliver');
mysql_select_db('users', $connection) or die(mysql_error());
?>
Information
When I click the delete button in data_display.php, I do receive the javascript alert to confirm that I do want to delete the user from the database, but nothing actually happens.
if (isset($_GET['recordId'])) {
$id = mysql_real_escape_string($_GET['recordId']);
$sql_delete = "DELETE FROM users WHERE id = '{$id}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
You are sending recordId as parameter.

infinite scrolling system, need change method of getting last item

Here is code for infinite scrolling, so the thing is that when you scroll it adds #/page/3 to my link www.site.com/scroll.php#/page/2
So I want it to not do this, and my link stay clean, as I understand, it takes information about last item from link, and downloads data based on that number, I tried to change link to id but nothing is working, so here is code of scroll
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="scripts/dist/jquery-ias.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Infinite Ajax Scroll configuration
jQuery.ias({
container : '.wrap', // main container where data goes to append
item: '.item', // single items
pagination: '.nav', // page navigation
next: '.nav a', // next page selector
loader: '<img src="css/ajax-loader.gif"/>', // loading gif
triggerPageThreshold: 12 // show load more if scroll more than this
});
});
</script>
<?php
include('config.php');
$page = (int) (!isset($_GET['p'])) ? 1 : $_GET['p'];
# sql query
$sql = "SELECT * FROM news ORDER BY news_id DESC";
# find out query stat point
$start = ($page * $limit) - $limit;
# query for page navigation
if( mysql_num_rows(mysql_query($sql)) > ($page * $limit) ){
$next = ++$page;
}
$query = mysql_query( $sql . " LIMIT {$start}, {$limit}");
?>
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jQuery Load While Scroll</title>
</head>
<body>
<div class="wrap">
<h1>Data load while scroll</h1>
<!-- loop row data -->
<?php while ($row = mysql_fetch_array($query)): ?>
<div class="item" id="item-<?php echo $row['news_id']?>">
<h2>
<span class="num"><?php echo $row['news_id']?></span>
<span class="name"><?php echo $row['subject'].' '.$row['news']?></span>
</h2>
<p><?php echo $row['picture1']?></p>
</div>
<?php endwhile?>
<!--page navigation-->
<?php if (isset($next)): ?>
<div class="nav">
<a href='scroll.php?p=<?php echo $next?>'>Next</a>
</div>
<?php endif?>
</div><!--.wrap-->
</body>
</html>
here is a config.php
<?php
# db configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'mysql');
$limit = 15; #item per page
# db connect
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect to MySQL DB ') . mysql_error();
$db = mysql_select_db(DB_NAME, $link);
?>
I'm not really fan of Infinity Scroll but you should look inside the plugin near the line 250. the function try to determine your next URl by checking the href of your link.
You should change it and return the right value of the path variable
_determinepath: function infscr_determinepath(path)
hope it will helps

Categories