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' ");
Related
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...
I dont know whats wrong with the code , when i search from march 3 - march 12 , the march 12 transaction does not show.
Thank you very much , this would help me a lot.
What I want is to show the march 12 transaction , like the e.g. given below .
I want it to show transactions from this date , to the date chosen.
E.G.
This is where I input it
Picture 1
March 3-12 Sample
Picture 2
March 3-13 Sample
Picture 3
This is my code
<head>
<script>
$(function() {
$( "#tabs" ).tabs();
$('a[rel*=facebox]').facebox();
$( ".datepicker" ).datepicker();
});
$(document).ready(function(){
// Write on keyup event of keyword input element
$("#searchme").keyup(function(){
// When value of the input is not blank
if( $(this).val() != "")
{
// Show only matching TR, hide rest of them
$("#searchTbl tbody>tr").hide();
$("#searchTbl td:contains-ci('" + $(this).val() + "')").parent("tr").show();
}
else
{
// When there is no input or clean again, show everything back
$("#searchTbl tbody>tr").show();
}
});
});
// jQuery expression for case-insensitive filter
$.extend($.expr[":"],
{
"contains-ci": function(elem, i, match, array)
{
return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
</script>
<script>
function goBack() {
window.history.back();
}
</script>
<?php include('session.php'); ?>
<?php include('header.php'); ?>
<?php include('navbar.php'); ?>
<style>
.logo1 {
position: absolute;
right: 45%;
font-family: ""Lucida Console", Monaco, monospace";
top: 0%;
width: 80%;
background-color:#F8F8FF;
color: black;
text-align: center;
}
h3{
font-size:20px;
font-family: "Arial";
}
table {
width:60%;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: center;
}
#media print {
#page { margin: 0; }
body { margin: 1cm; }
#printPageButton {
display: none;
}
#e{
display:none;
}
.footer {
position: fixed;
left: 0;
font-family: ""Lucida Console", Monaco, monospace";
bottom: 0;
width: 100%;
background-color:#F8F8FF;
color: black;
text-align: center;
}
}
</style>
<?php
if(isset($_POST['salesbtn'])) {
$from = date('Y-m-d', strtotime($_POST['dayfrom']))." 00:00:01";
$to = date('Y-m-d', strtotime($_POST['dayto']))." 23:59:59";
?>
</head>
<body>
<div style="height:50px;"></div>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-0">
<br><img src="../upload/logo.jpg" class="logo1" style="height:50px; width:50px;" ><br>
<center><h1>Inventory Report</h1><h3> From (<?php echo $from; ?>) To (<?php echo $to; ?>)</h3>
<br>
<button id="printPageButton" class="btn btn-primary" onClick="window.print();">Print</button>
<button id="e" class="btn btn-primary" onclick="goBack()">Back</button>
<br><br>
<table width="100%" cellspacing="0" cellpadding="0" style="font-family:Arial Narrow, Arial,sans-serif; font-size:15px;" border="1">
<tr>
<th width="25%"><div align="center"><strong> Date </strong></div></th>
<th width="20%"><div align="center"><strong> User</strong></div></th>
<th width="20%"><div align="center"><strong>Action</strong></div></th>
<th width="20%"><div align="center"><strong>Product Name</strong></div></th>
<th width="20%"><div align="center"><strong>Quantity </strong></div></th>
</tr>
<?php
$iq=mysqli_query($conn,"select * from inventory left join product on product.productid=inventory.productid where inventory_date BETWEEN CAST('$from' AS DATE) AND CAST('$to' AS DATE) order by inventory_date desc ");
while($iqrow=mysqli_fetch_array($iq)){
?>
<tr>
<td class="hidden"></td>
<td><?php echo date('M d, Y h:i A',strtotime($iqrow['inventory_date'])); ?></td>
<td>
<?php
$u=mysqli_query($conn,"select * from `user` left join customer on customer.userid=user.userid left join supplier on supplier.userid=user.userid where user.userid='".$iqrow['userid']."'");
$urow=mysqli_fetch_array($u);
if($urow['access']==1){
echo "Admin";
}
elseif($urow['access']==2){
echo $urow['customer_name'];
}
else{
echo $urow['company_name'];
}
?>
</td>
<td align="right"><?php echo $iqrow['action']; ?></td>
<td align="right"><?php echo $iqrow['product_name']; ?></td>
<td align="right"><?php echo $iqrow['quantity']; ?></td>
</tr>
<?php
} }
?>
</tr> </td>
</br> </br>
<td style="color:red;" align="center"> Total:<?php
try {
require ("conn.php");
$stmt = $conn->prepare("SELECT SUM(sales_total) as 'test' FROM sales WHERE sales_date BETWEEN '$from' AND '$to'");
$stmt->execute();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
echo $row['test'];
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
</table>
</div>
</div>
</div>
<?php include('script.php'); ?>
<?php include('modal.php'); ?>
<?php include('add_modal.php'); ?>
<script src="custom.js"></script>
The problem is occurring because you are casting your $to value as a DATE, which implies a TIME portion of 00:00:00. The BETWEEN then fails because '2018-03-12 11:31:25' is not <= '2018-03-12 00:00:00'
Changing the CAST of $to to a DATETIME should fix the problem. i.e.
$iq=mysqli_query($conn,"select * from inventory left join product on product.productid=inventory.productid where inventory_date BETWEEN CAST('$from' AS DATE) AND CAST('$to' AS DATETIME) order by inventory_date desc ");
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"]);
?>
This question already has answers here:
Checking if mysqli_query returned any values?
(2 answers)
Closed 1 year ago.
I have a report, which has a few prompts, and based on the prompt selection, sometimes there might be no records in the report. In such cases, I want to show a message NO RECORDS FOUND on the Cover Page.
Can anyone tell me how I do this?
<?php
error_reporting(0);
include("connection.php");
session_start();
if(!($_SESSION['email']))
{
echo "please login first to access this page";
header("refresh:3;url=index.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
body
{
margin: 0;
padding: 0;
}
table
{
border-collapse: collapse;
width: 100%;
font-family: sans-serif;
font-size: 15px;
}
th,td
{
padding: 5px;
text-align: left;
}
tr:nth-child(even)
{
background: #edf0f5;
}
th
{
background: #00A800;
color: white;
padding: 5px;
font-family: sans-serif;
}
a
{
text-decoration: none;
color: #00A800;
}
a:hover
{
text-decoration: underline;
}
</style>
<title>View all the data</title>
</head>
<body>
<table>
<tr>
<th>Roll NO</th>
<th>Student Name</th>
<th>Father Name</th>
<th>Class</th>
<th>Class Section</th>
<th>Phone number</th>
<th>Email Address</th>
<th>Address</th>
<th>Edit</th>
<th>View Fees</th>
<th>Attendance</th>
</tr>
<?php
$select="select *from student where class='1' AND section='B' ";
$run=mysqli_query($con,$select);
$i=0;
while($row=mysqli_fetch_array($run))
{
$id=$row['id'];
$s_name=$row['s_name'];
$f_name=$row['f_name'];
$class=$row['class'];
$section=$row['section'];
$phone=$row['phone'];
$email=$row['email'];
$address=$row['address'];
$i++;
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $s_name;?></td>
<td><?php echo $f_name;?></td>
<td><?php echo $class;?></td>
<td><?php echo $section;?></td>
<td><?php echo $phone;?></td>
<td><?php echo $email;?></td>
<td><?php echo $address;?></td>
<td>Edit</td>
<td>Fees</td>
<td>Attendance</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
You can use mysqli_num_rows() to check the number of rows in a result
$select = "select *from student where class='1' AND section='B' ";
$run = mysqli_query($con, $select);
if (mysqli_num_rows($run > 0)) {// check if your query return result
// your code
} else {
echo "NO result found";
}
Read http://php.net/manual/en/mysqli-result.num-rows.php
You need to check if rows are returned, if not, show error.
$i = 0;
while($row=mysqli_fetch_array($run)) {
// Your code
$i++;
}
if ($i <1) {
?>
<tr><td colspan="11">There are no records.</td></tr>
<?php
}
Explanation:
1) We have taken a variable $i, initialized to 0
2) In while loop, it is incremented.
3) If we have records, after while loop, we will get $i more than 0.
4) If it is still 0 that is less than 1, it means there are no records and show the error message.
You can use mysqli_num_rows to count the number of rows returned:
Returns the number of rows in the result set.
Since, mysqli_num_rows will return 0 if there's no result, you can use ! to check if the result is false.
$select="select *from student where class='1' AND section='B' ";
$run=mysqli_query($con, $select);
if (!mysqli_num_rows($run)) {
echo "No result is found";
} else {
// to do if there's result
}
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);