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"]);
?>
Related
I have got many customers with the same first name/last name. But, all customers have a specific id(OL_ID). My task is when I click one customer's OL_ID in port.php, it should take to example.php and extract the particular customer's information.
I tried this following code and they are not working. It says "enter the correct OL_ID again!" for all id's. I know there is some mistake in example.php. I would be grateful if someone corrects this.
port.php
<?php
session_start();
//connect to DB
ini_set('display_errors', 0); //<- here you can switch on and off the error reporting 0 / 1
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$host = "localhost"; $username = "root"; $password = "mysqlr00tpa55";
try
{
$myconnection = new PDO("mysql:host=$host;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$myconnection ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//ECHO "TEST";
if(isset($_POST['submit']))
{
$sql = 'SELECT * FROM OL_trans WHERE';
if (!empty($_POST['vorname']))
//Vorname
{
$sql .= ' vorname = ? AND ';
$params[] = $_POST['vorname'];
}
if (!empty($_POST['nachname']))
//Nachname
{
$sql .= ' nachname = ? AND ';
$params[] = $_POST['nachname'];
}
if (!empty($_POST['email']))
//E-mail address
{
$sql .= ' email = ? AND ';
$params[] = $_POST['email'];
}
if (!empty($_POST['strasse']))
//Strasse
{
$sql .= ' strasse = ? AND ';
$params[] = $_POST['strasse'];
}
if ( !empty($_POST['ort']) )
//Ort
{
$sql .= ' ort= ? AND ';
$params[] = $_POST['ort'];
}
if ( !empty($_POST['plz']))
//Plz
{
$sql .= ' plz= ? AND ';
$params[] = $_POST['plz'];
}
if ( !empty($_POST['telefon']))
//Telefonnummer
{
$sql .= ' telefon=? AND ';
$params[] = $_POST['telefon'];
}
if( !empty($_POST['adrZus']))
//HausnummerZusatz
{
$sql .= ' adrZus=? AND ';
$params[] = $_POST['adrZus'];
}
if( !empty($_POST['hnr']))
//Hausnummer
{
$sql .= ' hnr=? AND ';
$params[] = $_POST['hnr'];
}
$sql = rtrim($sql, 'AND ');
$stmt = $myconnection->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();
foreach($rows as $row)
{
?>
<!DOCTYPE html>
<html>
<head>
<title>Data fetched</title>
</head>
<style>
body
{
background-image: url("background.gif");
color:white;
font-size:40px;
font-family:"times new roman", times, serif;
}
</style>
<body>
<br/><br/><table align="center" border="3px" style="width:75%; line-height:40px; background-color:#616263">
<t>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Customer id</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Vorname</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Nachname</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Email Id</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Strasse</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Ort</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Plz</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Telefon</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Mobil</th>
</t>
<tr align="center">
<td style="cursor: pointer;">
<?php echo $row['OL_ID']; ?></td>
<td><?php echo $row['vorname'];?></td>
<td><?php echo $row['nachname'];?></td>
<td><?php echo $row['email'];?></td>
<td><?php echo $row['strasse'];?></td>
<td><?php echo $row['ort'];?></td>
<td><?php echo $row['plz'];?></td>
<td><?php echo $row['mobil'];?></td>
</tr>
</table>
</body>
</html>
<?php
}
}else
{
echo"Enter the correct information again!";
}
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<html>
<head></head>
</head>
<style>
button[type=button1]
{
border-radius: 40px 10px 35px 8px;
width: 170px;height:60px;
padding-left: 3px;
color: white;
text-shadow: 2px 1px;
font-size: 28px;
background-color:rgba(238, 130, 7, 0.9);
font-weight:bolder;
}
button[type=button1]:hover
{
background-image: url("background.gif");
cursor: pointer;
color: white;
font-size:32px;
box-shadow:2px 5px;
}
</style>
<body>
<br/>
<button type="button1" onclick="goBack()"/>Zurück</button>
<script>
function goBack()
{
window.history.back();
}
</script>
</body>
</html>
Here is example.php:
When I click OL-ID in port.php, it should extract the customer's information on selected OL_ID
<?php
//connect to DB
ini_set('display_errors', 1); //<- here you can switch on and off the error reporting 0 / 1 - makes life easy ;)
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//echo $_POST['vorname'];
$debug=1;
$host = "localhost"; $username = "root"; $password = "mysqlr00tpa55";
try {
$myconnection = new PDO("mysql:host=$host;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$myconnection ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['submit'])){
$num=$_POST['OL_ID'];
$statement = $myconnection->prepare("SELECT * FROM OL_trans WHERE OL_ID LIKE '$num' ");
$statement->execute();
$key = $statement->fetchall();
foreach($key as $value){ ?>
<!DOCTYPE html>
<html>
<head>
<title>Data fetched</title>
</head>
<style>
body{
background-image: url("background.gif");
color: white;
font-weight: bolder;
font-size: 40px;
font-family: sans-serif serif cursive;
padding-top: 105px; }
</style>
<body>
<br/><br/><table align="center" border="3px" style="width:70%; line-height:80px; background-color:#616261">
<t>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Customer id</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Vorname</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Nachname</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Email Id</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Strasse</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Ort</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Plz</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Telefon</th>
<th style="color:rgba(238, 130, 7, 0.9); font-size:25px">Mobil</th>
</t>
<tr align="center">
<td><?php echo $value['OL_ID']; ?></a></td>
<td><?php echo $value['vorname']; ?></td>
<td><?php echo $value['nachname']; ?></td>
<td><?php echo $value['email']; ?></td>
<td><?php echo $value['strasse']; ?></td>
<td><?php echo $value['ort']; ?></td>
<td><?php echo $value['plz']; ?></td>
<td><?php echo $value['telefon']; ?></td>
<td><?php echo $value['mobil']; ?></td>
</tr>
</table>
</body>
</html>
<?php
}
}
else{
echo "enter the corect OL_ID again!";
}
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<html>
<head></head>
<style>
button[type=button1]{
border-radius: 40px 10px 35px 8px;
width: 160px;height:55px;
padding-left: 3px;
color: white;
text-shadow: 2px 1px;
font-size: 28px;
background-color:rgba(238, 130, 7, 0.9);
font-weight:bolder;
}
button[type=button1]:hover{
background-image: url("background.gif");
cursor: pointer;
color: white;
font-size:32px;
box-shadow: 2px 5px;
}
</style>
<body>
<br/>
<button type="button1" onclick="goBack()"/>Zurück</button>
<script>
function goBack() {window.history.back();}
</script>
</body>
</html>
Firstly, you're missing a question mark (and a param name) in port.php. Change this:
<?php echo $row['OL_ID']; ?>
to this:
<?php echo $row['OL_ID']; ?>
Secondly, access the now passed id param via $_GET in example.php instead of $_POST. Change this:
if(isset($_POST['submit'])){
$num=$_POST['OL_ID'];
to this:
if(isset($_GET['id'])){
$num=$_GET['id'];
Thirdly, read about SQL injections regarding this line:
$statement = $myconnection->prepare("SELECT * FROM OL_trans WHERE OL_ID LIKE '$num' ");
I'm trying to upload an excel file to a mysql DB using PHP. I've got this working.
However, if I refresh the page or upload again another file, it gets duplicated.
I would like before it uploads a new file to clear (truncate) the table and then insert the new data.
Bue I cannot find where to put or how to put the TRUNCATE TABLE existencias_2018; if the Submit button is clicked and before it inserts the data.
Another issue is the refreshing thing. It is a way to stop the refresh after I've uploaded the data? Or a way that refreshing doesn't duplicate it?
So in summary the help i need is:
Where to put and how the TRUNCATE TABLE existencias_2018;.
Stop duplicating data if page gets refreshed.
Here is my piece of code:
<?php
$conn = mysqli_connect("localhost","root","","papa");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"])){
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++){
$Reader->ChangeSheet($i);
foreach ($Reader as $Row){
$model = "";
if(isset($Row[0])) {
$model = mysqli_real_escape_string($conn,$Row[0]);
}
$cup = "";
if(isset($Row[1])) {
$cup = mysqli_real_escape_string($conn,$Row[1]);
}
$color = "";
if(isset($Row[1])) {
$color = mysqli_real_escape_string($conn,$Row[2]);
}
$description = "";
if(isset($Row[1])) {
$description = mysqli_real_escape_string($conn,$Row[3]);
}
$size36 = "";
if(isset($Row[1])) {
$size36 = mysqli_real_escape_string($conn,$Row[4]);
}
$size38 = "";
if(isset($Row[1])) {
$size38 = mysqli_real_escape_string($conn,$Row[5]);
}
$size40 = "";
if(isset($Row[1])) {
$size40 = mysqli_real_escape_string($conn,$Row[6]);
}
$size42 = "";
if(isset($Row[1])) {
$size42 = mysqli_real_escape_string($conn,$Row[7]);
}
$size44 = "";
if(isset($Row[1])) {
$size44 = mysqli_real_escape_string($conn,$Row[8]);
}
$size46 = "";
if(isset($Row[1])) {
$size46 = mysqli_real_escape_string($conn,$Row[9]);
}
$size48 = "";
if(isset($Row[1])) {
$size48 = mysqli_real_escape_string($conn,$Row[10]);
}
$size50 = "";
if(isset($Row[1])) {
$size50 = mysqli_real_escape_string($conn,$Row[11]);
}
$size52 = "";
if(isset($Row[1])) {
$size52 = mysqli_real_escape_string($conn,$Row[12]);
}
$size54 = "";
if(isset($Row[1])) {
$size54 = mysqli_real_escape_string($conn,$Row[13]);
}
if (!empty($model) || !empty($cup) || !empty($color) || !empty($description) || !empty($size36) || !empty($size38) || !empty($size40) || !empty($size42) || !empty($size44) || !empty($size46) || !empty($size48) || !empty($size50) || !empty($size52) || !empty($size54)) {
$query = "insert into existencias_2018(model,cup,color,description,size36,size38,size40,size42,size44,size46,size48,size50,size52,size54) values('".$model."','".$cup."','".$color."','".$description."','".$size36."','".$size38."','".$size40."','".$size42."','".$size44."','".$size46."','".$size48."','".$size50."','".$size52."','".$size54."')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
$type = "success";
$message = "Datos de Excel importados en la base de datos satisfactoriamente";
} else {
$type = "error";
$message = "Ha habido un problema al importar los datos de Excel";
}
}
}
}
}else{
$type = "error";
$message = "Tipo de archivo invalido. Suba un archivo de Excel.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial;
width: 1000px;
}
.outer-container {
background: #F0F0F0;
border: #e0dfdf 1px solid;
padding: 40px 20px;
border-radius: 2px;
}
.btn-submit {
background: #333;
border: #1d1d1d 1px solid;
border-radius: 2px;
color: #f0f0f0;
cursor: pointer;
padding: 5px 20px;
font-size:0.9em;
}
.tutorial-table {
margin-top: 40px;
font-size: 0.8em;
border-collapse: collapse;
width: 100%;
}
.tutorial-table th {
background: #f0f0f0;
border-bottom: 1px solid #dddddd;
padding: 8px;
text-align: left;
}
.tutorial-table td {
background: #FFF;
border-bottom: 1px solid #dddddd;
padding: 8px;
text-align: left;
}
#response {
padding: 10px;
margin-top: 10px;
border-radius: 2px;
display:none;
}
.success {
background: #c7efd9;
border: #bbe2cd 1px solid;
}
.error {
background: #fbcfcf;
border: #f3c6c7 1px solid;
}
div#response.display-block {
display: block;
}
</style>
</head>
<body>
<h2>Importar existencias actualizadas</h2>
<div class="outer-container">
<form action="" method="post"
name="frmExcelImport" id="frmExcelImport" enctype="multipart/form-data">
<div>
<label>Buscar archivo Excel</label>
<input type="file" name="file" id="file" accept=".xls,.xlsx">
<button type="submit" id="submit" name="import" class="btn-submit">Importar</button>
</div>
</form>
</div>
<div id="response" class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
<?php
$sqlSelect = "SELECT * FROM existencias_2018";
$result = mysqli_query($conn, $sqlSelect);
if (mysqli_num_rows($result) > 0){
?>
<table class='tutorial-table'>
<thead>
<tr>
<th>Modelo</th>
<th>Copa</th>
<th>Color</th>
<th>Descripcion</th>
<th>36</th>
<th>38</th>
<th>40</th>
<th>42</th>
<th>44</th>
<th>46</th>
<th>48</th>
<th>50</th>
<th>52</th>
<th>54</th>
</tr>
</thead>
<?php
$sql = "TRUNCATE TABLE existencias_2018";
while ($row = mysqli_fetch_array($result)) {
?>
<tbody>
<tr>
<td><?php echo $row['model']; ?></td>
<td><?php echo $row['cup']; ?></td>
<td><?php echo $row['color']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><?php echo $row['size36']; ?></td>
<td><?php echo $row['size38']; ?></td>
<td><?php echo $row['size40']; ?></td>
<td><?php echo $row['size42']; ?></td>
<td><?php echo $row['size44']; ?></td>
<td><?php echo $row['size46']; ?></td>
<td><?php echo $row['size48']; ?></td>
<td><?php echo $row['size50']; ?></td>
<td><?php echo $row['size52']; ?></td>
<td><?php echo $row['size54']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</body>
</html>
Is that what you want ?
<?php
$conn = mysqli_connect("localhost","root","","papa");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"])){
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
// Looks like we have a correct file to upload.
// Let's TRUNCATE the table first :
$query = "TRUNCATE TABLE existencias_2018;";
mysqli_query($conn, $query);
// OK, table is empty, proceed with upload....
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++){
$Reader->ChangeSheet($i);
foreach ($Reader as $Row){
$model = "";
if(isset($Row[0])) {
$model = mysqli_real_escape_string($conn,$Row[0]);
}
// and so on...
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;
}
}
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);
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']; ?>