This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 3 years ago.
I have a little problem with Ajax and MySQL in my application.
My application it is a some thing like user manager. I have MySQL database with ID, USERNAME, PASSWORD, FIRST_NAME, LAST_NAME and EMAIL field.
I made list of users pagination 10 records per page. And now I'm trying to make functionality for adding new users, editing existing users and to delete users one by one.
I have next code:
Config.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "password";
$mysql_database = "mybase";
$con = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps error! occurred");
mysql_select_db($mysql_database, $con) or die("Opps error! occurred");
?>
This is database connection
**
index.php
**
<?php
include('config.php');
$per_page = 3;
//getting number of rows and calculating no of pages
$sql = "select count(*) from users";
$result = mysql_query($sql);
$count = mysql_fetch_row($result);
$pages = ceil($count[0]/$per_page);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Users Manager</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="pagination.js"></script>
<style>
body { margin: 0; padding: 0; font-family:Verdana; font-size:15px }
a
{
text-decoration:none;
color:#B2b2b2;
}
a:hover
{
color:#DF3D82;
text-decoration:underline;
}
#loading {
width: 100%;
position: absolute;
}
#pagination
{
text-align:center;
margin-left:120px;
}
li{
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}
li:hover
{
color:#FF0084;
cursor: pointer;
}
</style>
</head>
<body>
<div align="center">
<div style="margin-top:50px;"><b>Title</b>: users Manager</div>
<div id="content" ></div>
<table width="800px">
<tr><Td>
<ul id="pagination">
<?php
//Show page links
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
?>
</ul>
</Td>
</tr></table>
<div id="loading" ></div>
</div>
</body>
</html>
**
data.php
**
<?php
include('config.php');
$per_page = 10;
if($_GET)
{
$page=$_GET['page'];
}
//getting table contents
$start = ($page-1)*$per_page;
$sql = "select * from users order by id limit $start,$per_page";
$rsd = mysql_query($sql);
if(isset($_POST['buttonsave'])){
$query_sql = "INSERT INTO users (username,firstname,lastname,email) VALUES ('{$_POST[username]}','{$_POST[firstname]}','{$_POST[lastname]}','{$_POST[email]}')";
$result = mysql_query($query_sql);
if($result){
echo "Successful insert";
}
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<table id="tbl">
<th>User Name:<input type="text" id="username" name="username" placeholder="User"></th>
<th>First Name:<input type="text" id="firstname" name="firstname" placeholder="First Name"></th>
<th>Last Name:<input type="text" id="lastname" name="lastname" placeholder="Last Name"></th>
<th>E-mail:<input type="email" id="email" name="email" placeholder="Email"></th>
</table>
<input type="button" value="Insert" id="save">
<script type="text/javascript">
$(function(){
$("#save").click(function(){
var uname = $("#username").val();
var fname = $("#firstname").val();
var lname = $("#lastname").val();
var email = $("#email").val();
$.ajax({
url: "data.php",
type: "POST",
async: true,
data: {
buttonsave: 1,
username: uname,
firstname: fname,
lastname: lname,
email: email
},
success: function(result){
alert("OK! Good!");
}
});
});
});
</script>
<table id="tbl">
<th><b>Id</b></th>
<th><b>User Name</b></th>
<th><b>First Name</b></th>
<th><b>Last Name</b></th>
<th><b>E-mail</b></th>
<?php
while($row = mysql_fetch_array($rsd))
{
$id = $row['id'];
$uname = $row['username'];
$fname = $row['first_name'];
$lname = $row['last_name'];
$email = $row['email'];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $uname; ?></td>
<td><?php echo $fname; ?></td>
<td><?php echo $lname; ?></td>
<td><?php echo $email; ?></td>
</tr>
<?php
} //End while
?>
</table>
<style>
#tbl
{
width:800px;
border:1px solid #2E8AE6;
margin-top:50px;
}
#tbl tr:nth-child(odd) {
background: #C2E0FF;
}
#tbl td{
border:1px solid #2E8AE6;
padding: 5px;
}
#tbl th
{
background: #2E8AE6;
border:1px solid #2E8AE6;
padding: 5px;
}
</style>
and my jQuery file:
**
pagination.js
**
$(document).ready(function(){
//Loading Image Display
function Display_Load()
{
$("#loading").fadeIn(100);
$("#loading").html("<img src='loading.gif' />");
}
//Hide Loading Image
function Hide_Load()
{
$("#loading").fadeOut('slow');
};
//Default Starting Page Results
$("#pagination li:first").css({'color' : '#FF0084','border' : 'none'});
$("#content").load("data.php?page=1", Hide_Load());
//Pagination Click
$("#pagination li").click(function(){
Display_Load();
//CSS Styles
$("#pagination li")
.css({'border' : 'solid #dddddd 1px'})
.css({'color' : '#0063DC'});
$(this)
.css({'color' : '#FF0084'})
.css({'border' : 'none'});
//Loading Data
var pageNum = this.id;
$("#content").load("data.php?page=" + pageNum, Hide_Load());
});
});
So the problem is in my data.php.
I tried to insert data using ajax, but it does't work!
And it insert nothing to database.
But it alerts me
alert("OK! Good!");
I can't understand that is wrong. Please help.
if(isset($_POST['buttonsave'])){
$query_sql = "INSERT INTO users (id,username,first_name,last_name,email) VALUES ('','$_POST[username]','$_POST[firstname]','$_POST[lastname]','$_POST[email]')";
$result = mysql_query($query_sql);
if($result){
echo "Successful insert";
}
Related
I'm trying to implement autocomplete from sql database using bootsrap typeahead.
When I'm trying it out in a demo it works perfectly, but when I put it inside the project nothing works.
CSS
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="typeahead.js"></script>
<style>
.typeahead {}
.tt-menu { width:300px; }
ul.typeahead{margin:0px;padding:10px 0px;}
ul.typeahead.dropdown-menu li a {padding: 10px !important; border-bottom:#CCC 1px solid;color:#FFF;}
ul.typeahead.dropdown-menu li:last-child a { border-bottom:0px !important; }
.bgcolor {max-width: 550px;min-width: 290px;max-height:340px;padding: 100px 10px 130px;border-radius:4px;text-align:center;margin:10px;}
.demo-label {font-size:1.5em;color: #686868;font-weight: 500;color:#FFF;}
.dropdown-menu>.active>a, .dropdown-menu>.active>a:focus, .dropdown-menu>.active>a:hover {
text-decoration: none;
background-color: #1f3f41;
outline: 0;
}
</style>
here is the script and HTML code
<div class="form-group">
<label>Srtudent Name or ID<span style="color:red;">*</span></label>
<input class="typeahead form-control" type="text" name="studentID" id="studentID" />
</div>
<script>
$(document).ready(function () {
$('#studentID').typeahead({
source: function (query, result) {
$.ajax({
url: "search-student.php",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
});
</script>
Here's the PHP code
<?php
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'lms');
$sql = $conn->prepare("SELECT * FROM students WHERE studentName LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["studentName"];
}
echo json_encode($countryResult);
}
$conn->close();
?>
Put
<script type="text/javascript" src="typeahead.js"></script>
as last script so no override to happen for the function typeahead. (this solved the problem)
I'm trying to make a Chat Room using PHP ( It is working BTW ), but only the messages are displaying, not their usernames. I have created the Databases for them, username and msg. I don't know why their usernames aren't displaying
<? php
//$uname = $_REQUEST['uname'];
//$msg = $_REQUEST['msg'];
$uname = (isset($_REQUEST['uname']) ? $_REQUEST['uname'] : '');
$msg = (isset($_REQUEST['msg']) ? $_REQUEST['msg'] : null);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('chatbox', $con);
mysql_query("INSERT INTO logs (`username` , `msg`) VALUES ('$uname', '$msg')");
$result1 = mysql_query("SELECT * FROM logs ORDER by id DESC");
while ($extract = mysql_fetch_array($result1)) {
echo "<span class = 'uname'>".$extract['username'].
"</span>: <span class = 'msg'> ".$extract['msg'].
"</span><br/>";
}
?>
<?php $con=mysql_connect('localhost',
'root',
'');
mysql_select_db('chatbox',
$con);
$result1=mysql_query("SELECT * FROM logs ORDER by id DESC");
while($extract=mysql_fetch_array($result1)) {
echo"<span class = 'uname'>" . $extract['username'] ."</span>: <span class = 'msg'> " . $extract['msg'] ."</span><br/>";
}
?>
<?php ?>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<style>
* {
margin: 0;
}
body {
padding-right: 250px;
padding-left: 250px;
margin: 0;
background-color: darkkhaki;
}
textarea {
resize: none;
width: 100%;
height: 300px;
background-color: #efefef;
}
a {
background-color: cadetblue;
padding: 15px 25px 15px 25px;
text-decoration: none;
color: white;
}
a:hover {
background-color: chartreuse;
}
</style>
</head>
<body>
<form name="form1">
Enter your Username
<input type="text" name="uname">
<br/>Enter your Message
<br/>
<textarea name="msg"></textarea>
<br/>
<br/>
Send
<br/>
<br/>
<div id="chatlogs">
Loading Chat...
</div>
</form>
<script>
function submitChat() {
if (form1.uname.value == '' || form1.msg.value == '') {
alert('Please Input Username and Message');
return;
}
var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'insert.php?uname' + uname + '&msg=' + msg, true);
xmlhttp.send();
}
</script>
</body>
</html>
. Feel free to point out the mistakes.
Replace
insert.php?uname
with
insert.php?uname=
Updated Code:
xmlhttp.open('GET', 'insert.php?uname=' + uname + '&msg=' + msg, true);
You are not inserting uname
I have an input, in which a code is entered and filled the table below with information from mysql optenida, the question is that I want every time a code is entered, the table all the data is added (without deleting the previous ). I got the idea to do with Ajax, but do not know where to start. So you see there is an easier way that I'm not seeing (finding on google). I do not like to add this data to a table, I would like it to be temporarily (until the table is confirmed, will be added to the db).
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table>
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
require ("conectar.php");
$_SESSION["codigo"] = $_POST["input_codigo"];
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
?>
</table>
</body>
</html>
Maybe something like this i write below.
Added jQuery and Ajax request to get the data and then add it to the table.
Changed the PHP a little so that the main HTML is not returned if it is and AJAX request.
Hope it works for you (i didnt test it).
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
$bAjaxRequest = false;
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$bAjaxRequest = true;
}
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form action="index.php" method="post" id="frmQuery" name="frmQuery">
<input type="text" name="input_codigo" id="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table id="tblData" name="tblData">
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
} // end if(!$bAjaxRequest) {
// we are always going to return the TR's or ""
require ("conectar.php");
// ALWAYS, BUT ALWAYS VERIFY/VALIDATE USER INPUT!!!
$_SESSION["codigo"] = mysql_real_escape_string($_POST["input_codigo"]); // for example
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) { ?>
</table>
<script type="text/javascript">
function loadData(codigo) {
$.post( "index.php", { input_codigo: codigo }, function( data ) {
$("#tblData").append(data);
});
}
$(function() {
// jQuery POST are never cached, but if you change to GET you'll need this next line
//$.ajaxSetup ({ cache: false });
$("#frmQuery").submit(function(e) {
e.preventDefault();
loadData($("#input_codigo").val());
});
});
</script>
</body>
</html>
<?php
}
?>
what i want is when a user clicks a link it should automatically create two text box's at a time and from which we can click and create unlimited numbers of textboxs which when submitted it should save all the dynamically created textbox two text box's in a row.
meaning textboxA textboxB
in this manner......
I found a code on net which works very similar to that how i wanted...but instead of two textboxs it creates only one textbox at a time when clicked the link First i'll give u the full original code...
1) index.php
<?php
//Include the database class
require("classes/db.class.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>jQuery</title>
<script type="text/javascript" src="js/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="css/css.css" />
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<input id="field_' + count + '" name="fields[]' + '" type="text" /><br />' );
});
});
</script>
<body>
<?php
//If form was submitted
if (isset($_POST['btnSubmit'])) {
//create instance of database class
$db = new mysqldb();
$db->select_db();
//Insert static values into users table
$sql_user = sprintf("INSERT INTO users (Username, Password) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['name']),
mysql_real_escape_string($_POST['password']) );
$result_user = $db->query($sql_user);
//Check if user has actually added additional fields to prevent a php error
if ($_POST['fields']) {
//get last inserted userid
$inserted_user_id = $db->last_insert_id();
//Loop through added fields
foreach ( $_POST['fields'] as $key=>$value ) {
//Insert into websites table
$sql_website = sprintf("INSERT INTO websites (Website_URL) VALUES ('%s')",
mysql_real_escape_string($value) );
$result_website = $db->query($sql_website);
$inserted_website_id = $db->last_insert_id();
//Insert into users_websites_link table
$sql_users_website = sprintf("INSERT INTO users_websites_link (UserID, WebsiteID) VALUES ('%s','%s')",
mysql_real_escape_string($inserted_user_id),
mysql_real_escape_string($inserted_website_id) );
$result_users_website = $db->query($sql_users_website);
}
} else {
//No additional fields added by user
}
echo "<h1>User Added, <strong>" . count($_POST['fields']) . "</strong> website(s) added for this user!</h1>";
//disconnect mysql connection
$db->kill();
}
?>
<?php if (!isset($_POST['btnSubmit'])) { ?>
<h1>New User Signup</h1>
<form name="test" method="post" action="">
<label for="name">Username:</label>
<input type="text" name="name" id="name" />
<div class="spacer"></div>
<label for="name">Password:</label>
<input type="text" name="password" id="password" />
<div class="spacer"></div>
<div id="container">
<p id="add_field"><span>ยป Add your favourite links.....</span></p>
</div>
<div class="spacer"></div>
<input id="go" name="btnSubmit" type="submit" value="Signup" class="btn" />
</form>
<?php } ?>
</body>
</html>
2) db.class.php
<?php
class mysqldb {
/*
FILL IN YOUR DATABASE DETAILS BEFORE RUNNING THE EXAMPLE
*/
var $hostname = "localhost";
var $username = "root";
var $password = "mypassword";
var $database = "unlimited";
function db_connect() {
$result = mysql_connect($this->hostname,$this->username,$this->password);
if (!$result) {
echo 'Connection to database server at: '.$this->hostname.' failed.';
return false;
}
return $result;
}
function select_db() {
$this->db_connect();
if (!mysql_select_db($this->database)) {
echo 'Selection of database: '.$this->database.' failed.';
return false;
}
}
function query($query) {
$result = mysql_query($query) or die("Query failed: $query<br><br>" . mysql_error());
return $result;
mysql_free_result($result);
}
function fetch_array($result) {
return mysql_fetch_array($result);
}
function num_rows($result) {
return mysql_num_rows($result);
}
function last_insert_id() {
return mysql_insert_id();
}
function kill() {
mysql_close();
}
}
?>
3) css.css
html, input {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 0.8em;}
body { width: 500px; margin: 50px auto 0 auto; display: block;}
h1 { font-size: 1.5em; color: #333; }
input { font-size: 0.9em; padding: 5px; border: 1px solid #ccc; margin: 0; display: block;}
a { text-decoration: none; color: #666; font-weight: bold; }
a:hover { color: #ff0000; }
#divTxt { width:400px; padding: 5px; }
p a img { border: none; vertical-align: middle; }
.spacer {clear: both; height: 10px; }
.btn { width: 90px; font-weight: bold; }
#container { border: 1px solid #ccc; padding: 2px; }
.clear {overflow: hidden;width: 100%;
}
4) JQUERY.js
With this code i am only allowed to dynamically create one textbox when clicked the link as i said earlier, so to make it for my use as i wanted to have two textbox's i have edited the jquery part in the index.php page as below...
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<label for="fields[]' + '">Colour</label><input id="field_' + count + '" name="fields[]' + '" type="text" /><label for="fields2[]' + '">Quantity</label><input id="field2_' + count + '" name="fields2[]' + '" type="text" /><br />');
});
});
</script>
Till here i am successfull... but the main problem is I cannot save them both the two textbox's in a row in mysql table..
Please review this code and reply me if u get any answers.....
I'll surely click the green arrow for the working answer as accepted answer..
Please HELP guys......
Try this
jQuery
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<label for="field_'+count+'_1">Name</label><input id="field_'+count+'_1" name="fields[]['name']" type="text" /><label for="field2_'+count+'_2">URL</label><input id="field2_'+count+'_2" name="fields[]['url']" type="text" /><br />');
});
});
</script>
PHP
//Insert into websites table
$sql_website = sprintf("INSERT INTO websites (Website_Name,Website_URL) VALUES ('%s','%s')",
mysql_real_escape_string($value['name']),
mysql_real_escape_string($value['url']) );
$result_website = $db->query($sql_website);
$inserted_website_id = $db->last_insert_id();
I am assuming that the 1st column is Website_Name and the 2nd column is Website_URL
P.S. : You've said it creates two text boxes, which means there should be two table fields where you want to add those two values. But in your MySQL query, there is only one column insert.
"INSERT INTO websites (Website_URL) VALUES ('%s')"
Specify the 2nd column name to answer your question correctly.
I have an editable grid where I want to edit the CSS such that the textarea to show the maximum width, but somehow I can't increase the width of the text area.
My database has three columns:
ID
Name
Gossip
I'm retrieving everything and displaying it in an editable grid using PHP.
index.php code
<?php
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
die('Check the database connection again!');
}
$userQuery = 'SELECT Id,Name,Gossip FROM bollywood';
$stmt = $db->query($userQuery);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var textBefore = '';
$('#grid').find('td input').hover(function() {
textBefore = $(this).val();
$(this).focus();
}, function() {
var $field = $(this),
text = $field.val();
$(this).blur();
// Set back previous value if empty
if (text.length <= 0) {
$field.html(textBefore);
} else if (textBefore !== text) {
// Text has been changed make query
var value = {
'row': parseInt(getRowData($field)),
'column': parseInt($field.closest('tr').children().find(':input').index(this)),
'text': text
};
$.post('user.php', value)
.error(function() {
$('#message')
.html('Make sure you inserted correct data')
.fadeOut(3000)
.html(' ');
$field.val(textBefore);
})
.success(function() {
$field.val(text);
});
} else {
$field.val(text);
}
});
// Get the id number from row
function getRowData($td) {
return $td.closest('tr').prop('class').match(/\d+/)[0];
}
});
</script>
<title></title>
</head>
<body>
<?php if ($stmt): ?>
<div id="grid">
<p id="message">Click on the field to Edit Data</p>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gossip</th>
</tr>
</thead>
<tbody>
<?php while ($row = $stmt->fetch_assoc()): ?>
<tr class="<?php echo $row['Id']; ?>">
<td><input type="text" value="<?php echo $row['Id']; ?>" /> </td>
<td><input type="text" value="<?php echo $row['Name']; ?>" /></td>
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<?php else: ?>
<p>No actors added yet</p>
<?php endif; ?>
</body>
</html>
user.php code
<?php
// Detect if there was XHR request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$fields = array('row', 'column', 'text');
$sqlFields = array('Id', 'Name', 'Gossip');
foreach ($fields as $field) {
if (!isset($_POST[$field]) || strlen($_POST[$field]) <= 0) {
sendError('No correct data');
exit();
}
}
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
sendError('Connect error');
exit();
}
$userQuery = sprintf("UPDATE bollywood SET %s='%s' WHERE Id=%d",
$sqlFields[intval($_POST['column'])],
$db->real_escape_string($_POST['text']),
$db->real_escape_string(intval($_POST['row'])));
$stmt = $db->query($userQuery);
if (!$stmt) {
sendError('Update failed');
exit();
}
}
header('Location: index.php');
function sendError($message) {
header($_SERVER['SERVER_PROTOCOL'] .' 320 '. $message);
}
style.css code
body {
font: normal 14px Comic Sans, Comic Sans MS, cursive;
}
table {
width: 500px;
}
td, th {
border: 1px solid #d8d8bf;
}
th {
padding: 5px;
font: bold 14px Verdana, Arial, sans-serif;
}
td {
padding: 10px;
width: 200px;
}
td input {
margin: 0;
padding: 0;
// width:200px;
font: normal 14px sans-serif;
/** Less flicker when :focus adds the underline **/
border: 1px solid #fff;
}
td input:focus {
outline: 0;
border-bottom: 1px dashed #ddd !important;
}
#grid input {
// width: 200%;
}
You doing it wrong
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
Should be:
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
textarea is html tag name but not input type. so change this.
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
to
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
also add this css.
<style>
textarea {
resize: both;
width:700px;
}
</style>
also are you sure that you can get content using this.
<?php echo $row['Gossip']; ?>