query WHERE id='.$_GET['selected"] not working as intended - php

I need to allow my user to choose an option value in a dropdown list, upon which the page will refresh and columns from the DB will be update on the page. How can I set this behavior?
<script language="JavaScript">
// this js autorehresh page if option was change
function MM_jumpMenu(targ,selObj,restore){ //v3.0
eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
if (restore) selObj.selectedIndex=0;
}
</script>
<?php
//at first we must connect to DB
//external
require ('connectDB.php');
?>
<form method="post">
<select name="selected" onChange="MM_jumpMenu('parent',this,1)">
<?php
**// echo all id in table to options dropdown menu**
$sql='SELECT id FROM lekcia1';
$result=mysql_query($sql) or die(mysql_error($db));
$a = 0;
while ($recording=mysql_fetch_array($result)){
$a ++;
echo '<option value="'.$recording['selected'].'"> '.$a.' </option>';
};
?>
</select>
</form>
**<?php
// query NOT WORK
$sql1='SELECT * FROM lekcia1 WHERE id='.$_GET['']; // Notice: Undefined index: selected
$result1=mysql_query($sql1) or die(mysql_error($db));
$recording1=mysql_fetch_array($result1);
?>**
<ul>
<li><?php echo $recording1['column1'];?></li>
<li><?php echo $recording1['column2'];?></li>
<li><?php echo $recording1['column3'];?></li>
</ul>

The query is still no-working so here is my correct code.
<html>
<head>
<script language="JavaScript">
// this js autorehresh page if option was change
function MM_jumpMenu(targ,selObj,restore){ //v3.0
eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
if (restore) selObj.selectedIndex=0;
}
</script>
</head>
<body>
<?php
$host='localhost'; // this will ususally be 'localhost', but can sometimes differ
$dbname='phpmyadmin'; // the name of the database that you are going to use for this project
$user='root'; // the USERNAME that you created, or were given, to access your database
$password=''; // the PASSWORD that you created, or were given, to access your database
$db = mysql_connect($host, $user, $password) or die("Neda sa pripojit k MySQL serveru: " . mysql_error());
mysql_select_db($dbname, $db) or die(mysql_error($db));
mysql_query('SET NAMES UTF8');
mysql_query('SET COLLATION_CONNECTION=uft8_general_ci');
?>
<form method="post">
<select name="selected" onChange="MM_jumpMenu('parent',this,1)">
<?php
// echo all id in table to options dropdown menu**
$sql='SELECT id FROM lekcia1';
$result=mysql_query($sql) or die(mysql_error($db));
$a = 0;
while ($recording=mysql_fetch_array($result)){
$a ++;
echo '<option value="'.$recording['selected'].'"> '.$a.' </option>';
};
?>
</select>
</form>
<?php
// query NOT WORK
$sql1="SELECT * FROM lekcia1 WHERE id='".$_POST['selected']."'"; // Notice: Undefined index: selected
$result1=mysql_query($sql1) or die(mysql_error($db));
$recording1=mysql_fetch_array($result1);
?>
<ul>
<li><?php echo $recording['nazov_lekcie'];?></li>
<li><?php echo $recording['cislo_ulohy'];?></li>
<li><?php echo $recording['nazov_ulohy'];?></li>
</ul>
<?php
//at first we must connect to DB
//external
//require ('connectDB.php');
?>
</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();
}

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.

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