It's me again, sorry...
I've been looking for the answer right in this forums, but there are no posts has been solved. I don't know if the questioner has been resolved the problems and not given a solved comment or something like that. All the comments/replies from the questioner is 'not work' or 'get some new errors' ect.
Now my scripts has worked before I put pagination scripts on them, but again errors in 'mysqli'. The errors are:
Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\paging\index.php on line 8
Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\paging\index.php on line 9
My scripts contained two files:
index.php:
<?php
$con = mysqli_connect("localhost", "root", "", "db_book") or die(mysqli_error($con));
$per_page = 3;
//getting number of rows and calculating no of pages
$sql = "SELECT COUNT(*) FROM flipbook";
$result = mysqli_query($sql);
$count = mysqli_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>DIGITAL LIBRARY</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;"></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>
and data.php:
<?php
$con = mysqli_connect("localhost", "root", "", "db_book");
$sql = mysqli_query($con,"SELECT b.*, title, author_name, url_flipbook, p.publisher_name, ct.cat_name FROM biblioflip AS b
LEFT JOIN mst_publisherflip AS p ON b.publisher_id=p.publisher_id
LEFT JOIN mst_catflip AS ct ON b.cat_id=ct.cat_id
ORDER BY flip_id limit $start,$per_page") or die(mysqli_error($con));
$per_page = 3;
if($_GET)
{
$page=$_GET['page'];
}
//getting table contents
$start = ($page-1)*$per_page;
?>
<table id="tbl">
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>Category</th>
<th>Link</th>
<?php
while($row = mysqli_fetch_array($result))
{
$title = $row['title'];
$author = $row['author_name'];
$publisher = $row['publisher_name'];
$category = $row['cat_name'];
$link = 'FLIPBOOK</td>';
?>
<tr>
<td><?php echo $title; ?></td>
<td><?php echo $author; ?></td>
<td><?php echo $publisher; ?></td>
<td><?php echo $category; ?></td>
<td><?php echo $link; ?></td>
</tr>
<?php
} //End while
mysqli_close($con);
?>
</table>
<style>
#tbl
{
width:800px;
border:1px solid #98bf21;
margin-top:50px;
}
#tbl tr:nth-child(odd) {
background: #EAF2D3
}
#tbl td{
border:1px solid #98bf21
}
#tbl th
{
background: #A7C942;
border:1px solid #98bf21
}
</style>
Thanks again...thank you...
best regards,
The error message is quite descriptive and clear: The first parameter to mysqli_query should be the connection handle.
Instead of $result = mysqli_query($sql);, use $result = mysqli_query($con, $sql);
Related
I need your help with this small issue as my developing level is not the best In the room ( faraway :-) )
I would like to spread the results of my SQL request in 3 columns.
After the first 37 entries, I would like the entries 38 to 74 are filling the column #2, and column #3 over 74...
I hope it is clear.
please find below the code of my page:
<title>TITLE</title>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#700;800;900&display=swap" rel="stylesheet">
<style>
body {background-color: #000000;}
table {
background-color: #000000;
border-collapse: collapse;
width: 100%;
}
table, .table {
color: #fff;
font-family: "Montserrat", sans-serif;
font-size: 18px;
font-weight:800;
font-weight:Extra-bold;
}
tr:nth-child(even) {
background-color: #60451e;
}
</style>
<div class="container">
<div class="row">
<?php
include_once("inc/db_connect.php");
$sqlQuery = "SELECT name, GROUP_CONCAT(id ORDER BY id SEPARATOR ' | ') as grouped_id FROM developers GROUP BY name";
$resultSet = mysqli_query($conn, $sqlQuery) or die("database error:". mysqli_error($conn));
?>
<table id="editableTable" class="table table-bordered">
<tbody>
<?php while( $developer = mysqli_fetch_assoc($resultSet) ) { ?>
<tr id="<?php echo $developer ['id']; ?>">
<td><?php echo $developer ['name']; ?><br> <span style="color: #ffc000">BOXES > <?php echo $developer ['grouped_id']; ?></span></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
and I would like to keep a formatting similar to this for each entry:
echo $developer ['name']; ?><br> <span style="color: #ffc000">BOXES > <?php echo $developer ['grouped_id']; ?></span>
Thank you in advance
MY dbMySql.PHP FILE CODING
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'dbtuts');
class DB_con
{
function __construct()
{
global $conn;
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASS) or die('localhost connection problem'.mysql_error());
mysql_select_db(DB_NAME);
}
public function insert($fname,$lname,$city)
{
$sql = "INSERT users(first_name,last_name,user_city)VALUES('$fname','$lname','$city')";
$res = mysql_query($sql);
return $res;
}
public function select()
{
// $db=new DB_con();
// $db->__construct();
$sql = "SELECT * FROM users";
$res=mysql_query($sql);
// return $conn;
return $res;
}
}
?>
MY index.php FILE
<?php
include_once 'dbMySql.php';
$con = new DB_con();
$table = "users";
$res=$con->select($table);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<center>
<div id="header">
<div id="content">
<label></label>
</div>
</div>
<div id="body">
<div id="content">
<table align="center">
<tr>
<th colspan="3">ADD</th>
</tr>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>City</th>
</tr>
<?php
while($row=mysql_fetch_row($res))
{
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[2]; ?></td>
<td><?php echo $row[3]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<div id="footer">
<div id="content">
<hr /><br/>
<label>Appxone Private Limited</label>
</div>
</div>
</center>
</body>
</html>
MY add_data.php FILE CODING
<?php
include_once 'dbMySql.php';
$con = new DB_con();
// data insert code starts here.
if(isset($_POST['btn-save']))
{
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$city = $_POST['city_name'];
$res=$con->insert($fname,$lname,$city);
if($res)
{
?>
<script>
alert('Record inserted...');
window.location='index.php'
</script>
<?php
}
else
{
?>
<script>
alert('error inserting record...');
window.location='index.php'
</script>
<?php
}
}
// data insert code ends here.
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Data Insert and Select Data Using OOP - By Cleartuts</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<center>
<div id="header">
<div id="content">
<label>PHP Data Insert and Select Data Using OOP - By Cleartuts</label>
</div>
</div>
<div id="body">
<div id="content">
<form method="post">
<table align="center">
<tr>
<td><input type="text" name="first_name" placeholder="First Name" required /></td>
</tr>
<tr>
<td><input type="text" name="last_name" placeholder="Last Name" required /></td>
</tr>
<tr>
<td><input type="text" name="city_name" placeholder="City" required /></td>
</tr>
<tr>
<td>
<button type="submit" name="btn-save"><strong>SAVE</strong></button></td>
</tr>
</table>
</form>
</div>
</div>
</center>
</body>
</html>
MY style.css Coding is
#charset "utf-8";
/* CSS Document */
*
{
margin:0;
padding:0;
}
#header
{
width:100%;
height:50px;
background:#00a2d1;
color:#f9f9f9;
font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-size:35px;
text-align:center;
}
#header a
{
color:#fff;
text-decoration:blink;
}
#body
{
margin-top:50px;
}
table
{
width:40%;
font-family:Tahoma, Geneva, sans-serif;
font-weight:bolder;
color:#999;
margin-bottom:80px;
}
table a
{
text-decoration:none;
color:#00a2d1;
}
table,td,th
{
border-collapse:collapse;
border:solid #d0d0d0 1px;
padding:20px;
}
table td input
{
width:97%;
height:35px;
border:dashed #00a2d1 1px;
padding-left:15px;
font-family:Verdana, Geneva, sans-serif;
box-shadow:0px 0px 0px rgba(1,0,0,0.2);
outline:none;
}
table td input:focus
{
box-shadow:inset 1px 1px 1px rgba(1,0,0,0.2);
outline:none;
}
table td button
{
border:solid #f9f9f9 0px;
box-shadow:1px 1px 1px rgba(1,0,0,0.2);
outline:none;
background:#00a2d1;
padding:9px 15px 9px 15px;
color:#f9f9f9;
font-family:Arial, Helvetica, sans-serif;
font-weight:bolder;
border-radius:3px;
width:100%;
}
table td button:active
{
position:relative;
top:1px;
}
#footer
{
margin-top:50px;
position:relative;
bottom:30px;
font-family:Verdana, Geneva, sans-serif;
}
all code is working and data insert successfully and show but if you see above first file i am using mysql,i want to use mysqli but issue is that when show $conn as a global variable (because mysqli needed 2 parameters) and use in mysqli($sql,$conn),error show undefined variable $conn why?
Use $this for access variables in your class
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'dbtuts');
class DB_con {
private $conn;
function __construct() {
$this->conn = mysqli_connect(DB_SERVER,DB_USER,DB_PASS) or die('localhost connection problem'.mysql_error());
mysqli_select_db($this->conn, DB_NAME);
}
public function insert($fname,$lname,$city) {
$sql = "INSERT users(first_name,last_name,user_city)VALUES('$fname','$lname','$city')";
$res = mysqli_query($this->conn, $sql);
return $res;
}
public function select() {
// $db=new DB_con();
// $db->__construct();
$sql = "SELECT * FROM users";
$res = mysqli_query($this->conn, $sql);
// return $conn;
return $res;
}
}
<?php
error_reporting(E_ALL);
ini_set('display_errors' ,1);
require "connection.php";
$query= "SELECT client_id, array_agg(insurance) AS insurance from vouchers WHERE parsing_date=CURRENT_DATE GROUP BY client_id ";
$result = pg_query($conn,$query);
?>
<!DOCTYPE html>
<html>
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<link href = "http://fonts.googleapis.com/css?family=Roboto:400">
<style>
.responstable {
margin: 1em 0;
width: 100%;
overflow: hidden;
background: #FFF;
color: #024457;
border-radius: 10px;
border: 1px solid #167F92;
word-wrap: break-word;
}
</style>
</head>
<body>
<div class="container-fluid">
<div>
<h1>Clients</h1>
</div>
<table class="responstable" rules='all' style='border-collapse: collapse;'>
<thead>
<tr>
<th>Client id</th>
<th>Insurance</th>
<th>Number of rows</th>
</tr>
</thead>
<?php
while($row = pg_fetch_array($result))
{
?>
<tbody>
<td><?php echo $row['client_id']; ?></td>
<td><?php echo $row['insurance']; ?></td>
<td><?php echo $row['rows'];?></td>
</tr>
<?php }
?> </tbody>
</table>
</div>
</body>
</html>
I have the code above to make my output from:
Client id Insurance
------------ ---------------
123 {"AA","EE","U"}
125 {"AA","UE"}
126 {"CU"}
124 {"UE"}
I want this:
Client id Number of rows Insurance
------------ ----------------------- --------------
123 3 rows AA,EE,U
125 2 rows AA,UE
126 1 rows CU
124 1 rows UE
Im not sure how to fix it, i tried add this line to my query:
concat(count(*), ' rows') AS rows
But it just gave me an error, any ideas on what I could do for the rows to come out and the "{" and '"' goes?
u can use explode function.
try this code
<?php while ( $row = pg_fetch_array ( $result ) ) { ?>
<tr>
<td><?php echo $row['client_id']; ?></td>
<td><?php echo implode(',',json_decode($row['insurance'])); ?></td>
<td><?php
$sRows = '';
if($row['iCnt'] > 0) {
$sRows = $row['iCnt']==1?' row':' rows';
}
echo ''.$row['iCnt'].$sRows;
?></td>
</tr>
JSON Parsing and Query issues are solved
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
require "connection.php";
$query = "SELECT client_id,
count(*) AS iCnt,
array_agg(insurance) AS insurance from vouchers
WHERE parsing_date=CURRENT_DATE GROUP BY client_id ";
$result = pg_query ( $conn, $query );
?>
<!DOCTYPE html>
<html>
<head>
<link
href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"
rel="stylesheet">
<link href="http://fonts.googleapis.com/css?family=Roboto:400">
<style>
.responstable {
margin: 1em 0;
width: 100%;
overflow: hidden;
background: #FFF;
color: #024457;
border-radius: 10px;
border: 1px solid #167F92;
word-wrap: break-word;
}
</style>
</head>
<body>
<div class="container-fluid">
<div>
<h1>Clients</h1>
</div>
<table class="responstable" rules='all' style='border-collapse: collapse;'>
<thead>
<tr>
<th>Client id</th>
<th>Insurance</th>
<th>Number of rows</th>
</tr>
</thead>
<tbody>
<?php while ( $row = pg_fetch_array ( $result ) ) { ?>
<tr>
<td><?php echo $row['client_id']; ?></td>
<td><?php echo implode(',',json_decode($row['insurance'])); ?></td>
<td><?php
$sRows = '';
if($row['iCnt'] > 0) {
$sRows = $row['iCnt']==1?' row':' rows';
}
echo ''.$row['iCnt'].$sRows;
?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</body>
</html>
Change you query like this
SELECT client_id, concat(cast(count(*) AS char),' rows')
This works good in mysql. You have to type cast integer to string for concatenation
http://www.mysqltutorial.org/mysql-cast/
For PostgreSQL it's should be like this,
SELECT client_id,
count(*) AS cnt,
''||count(*)||' rows' AS concatString
https://www.postgresql.org/docs/8.3/static/functions-string.html
You can add If and else like this on query
SELECT client_id,
CASE WHEN count(*)>0 THEN
CASE WHEN count(*)==1 THEN ''||count(*)||' row'
ELSE ''||count(*)||' rows' END
ELSE ''
END AS concatenatedString
I don't know about the performance
Postgres nested if in case query
You want to use array_to_string:
SELECT
client_id,
concat(count(*), ' rows'),
array_to_string(array_agg(insurance),',') AS insurance
FROM vouchers
WHERE parsing_date=CURRENT_DATE
GROUP BY client_id
I tried to render a table from MS-SQL Database to Webpage and i get this error.
I'm still new in PHP. Please help
Useraccess.php
<?php
$path = dirname(__FILE__);
require_once(dirname(__FILE__)."/simpleusers/config.inc.php");
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers->getUsers();
class SimpleUsers
{
private $mysqli , $stmt;
private $conn;
private $sessionName = "SimpleUsers";
public $logged_in = false;
public $userdata;
public $uPassword;
public $salt;
public function getUsers()
{
$sql = "SELECT DISTINCT userId, uUsername, uActivity, uCreated FROM users ORDER BY uUsername ASC";
$stmt = sqlsrv_query($this->conn, $sql);
if( $stmt == false){
throw new Exception("Query Failed:".sqlsrv_errors());
}
$stmt->execute();
$stmt->store_result();
if( $stmt->num_rows == 0){
return array();
}
$users = array();
$i = 0;
while( $stmt->fetch() )
{
$users[$i]["userId"] = $userId;
$users[$i]["uUsername"] = $username;
$users[$i]["uActivity"] = $activity;
$users[$i]["uCreated"] = $created;
$i++;
}
}
}
?>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">
* { margin: 0px; padding: 0px; }
body
{
padding: 30px;
font-family: Calibri, Verdana, "Sans Serif";
font-size: 12px;
}
table
{
width: 800px;
margin: 0px auto;
}
th, td
{
padding: 3px;
}
.right
{
text-align: right;
}
h1
{
color: #FF0000;
border-bottom: 2px solid #000000;
margin-bottom: 15px;
}
p { margin: 10px 0px; }
p.faded { color: #A0A0A0; }
</style>
</head>
<body>
<h1>User administration</h1>
<table cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>Username</th>
<th>Last activity</th>
<th>Created</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4" class="right">
Create new user | Logout
</td>
</tr>
</tfoot>
<tbody>
<?php foreach
( $users as $user ): ?>
<tr>
<td><?php echo $user["uUsername"]; ?></td>
<td class="right"><?php echo $user["uActivity"]; ?></td>
<td class="right"><?php echo $user["uCreated"]; ?></td>
<td class="right">Delete | User info | Change password</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
config.inc.php
<?php
$GLOBALS["serverName"] = "DESKTOP-KRF6KT7\SQLEXPRESS";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "sa";
$GLOBALS["pwd"] = "twinz0000";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"])
?>
Error Displayed
Warning: sqlsrv_query() expects parameter 1 to be resource, null given in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 26
Notice: Array to string conversion in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 29
Fatal error: Uncaught exception 'Exception' with message 'Query Failed:Array' in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php:29 Stack trace: #0 C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php(8): SimpleUsers->getUsers() #1 {main} thrown in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 29
Your conn class property is not set.
Before you call $stmt = sqlsrv_query($this->conn, $sql); you must set it up in sqlsrv_connect.
Try adding construct:
public function __construct()
{
$this->conn = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"]);
}
Useraccess.php
<?php
$path = dirname(__FILE__);
require_once(dirname(__FILE__)."/simpleusers/config.inc.php");
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers->getUsers();
class SimpleUsers
{
private $mysqli , $stmt;
private $conn;
private $sessionName = "SimpleUsers";
public $logged_in = false;
public $userdata;
public $uPassword;
public $salt;
public $conn=$GLOBALS["conn"] ;
public function getUsers()
{
$sql = "SELECT DISTINCT userId, uUsername, uActivity, uCreated FROM users ORDER BY uUsername ASC";
$stmt = sqlsrv_query($this->conn, $sql);
if( $stmt == false){
throw new Exception("Query Failed:".sqlsrv_errors());
}
$stmt->execute();
$stmt->store_result();
if( $stmt->num_rows == 0){
return array();
}
$users = array();
$i = 0;
while( $stmt->fetch() )
{
$users[$i]["userId"] = $userId;
$users[$i]["uUsername"] = $username;
$users[$i]["uActivity"] = $activity;
$users[$i]["uCreated"] = $created;
$i++;
}
}
}
?>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">
* { margin: 0px; padding: 0px; }
body
{
padding: 30px;
font-family: Calibri, Verdana, "Sans Serif";
font-size: 12px;
}
table
{
width: 800px;
margin: 0px auto;
}
th, td
{
padding: 3px;
}
.right
{
text-align: right;
}
h1
{
color: #FF0000;
border-bottom: 2px solid #000000;
margin-bottom: 15px;
}
p { margin: 10px 0px; }
p.faded { color: #A0A0A0; }
</style>
</head>
<body>
<h1>User administration</h1>
<table cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>Username</th>
<th>Last activity</th>
<th>Created</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4" class="right">
Create new user | Logout
</td>
</tr>
</tfoot>
<tbody>
<?php foreach
( $users as $user ): ?>
<tr>
<td><?php echo $user["uUsername"]; ?></td>
<td class="right"><?php echo $user["uActivity"]; ?></td>
<td class="right"><?php echo $user["uCreated"]; ?></td>
<td class="right">Delete | User info | Change password</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
config.inc.php
<?php
$GLOBALS["serverName"] = "DESKTOP-KRF6KT7\SQLEXPRESS";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "sa";
$GLOBALS["pwd"] = "twinz0000";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"]);
$GLOBALS["conn"] = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"] );
?>
Hope it will help.
I have these two items in my php.ini file enabled:
extension=php_pdo_sqlsrv_53_ts.dll
extension=php_sqlsrv_53_ts.dll
Which is what I had before. Using Wamp Server. PHP 5.3.13 all the same as before. What else am I missing that is not allowing this to connect to the SQL server.
After connection file code.
<?php
$GLOBALS["serverName"] = "localhost";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "root";
$GLOBALS["pwd"] = "";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"]);
$conn = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"]);
?>
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']; ?>