hi i am write code for edit data in php but some error are find at this time please fix.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chemistry_web";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_GET['ID'])){
$id=$_GET['ID'];
$sql="SELECT * FROM research_tab WHERE ID='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);}
//include_once 'connection.php';
// if (isset($_GET['ID'])){
// $id=$_GET['ID'];
// $query = "SELECT * FROM $tbl_name WHERE id='$id'";
// $result = mysql_query($query);
// $row = mysql_fetch_array($result);
// }
?>
<!DOCTYPE html>
<html>
Why give warning Undefined variable rows when i am defined variable in top of code.
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Education</title>
<link href="assets/plugins/bootstrap/bootstrap.css" rel="stylesheet" />
<link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<link href="assets/css/style.css" rel="stylesheet" />
<link href="assets/css/main-style.css" rel="stylesheet" />
<link href="assets/plugins/morris/morris-0.4.3.min.css" rel="stylesheet" />
</head>
<body>
<div id="wrapper">
<nav class="navbar navbar-default navbar-fixed-top" role="navigation" id="navbar">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="dashboard.html">
<img src="assets/img/logo.png" alt="Chemistry"/>
</a>
</div>
<ul class="nav navbar-top-links navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-user fa-3x"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><i class="fa fa-sign-out fa-fw"></i>Logout
</li>
</ul>
</li>
</ul>
</nav>
<nav class="navbar-default navbar-static-side" role="navigation">
<div class="sidebar-collapse">
<ul class="nav" id="side-menu">
<li class="sidebar-search">
</li>
<li class="selected">
<i class="fa fa-dashboard fa-fw"></i>Dashboard
</li>
<li>
<i class="fa fa-files-o fa-fw"></i>Home Page Settings<span class="fa arrow"></span>
<ul class="nav nav-second-level">
<li>
Research Settings
</li>
</ul>
</li>
</ul>
</div>
</nav>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Research Settings</h1>
</div>
</div>
<form action="#" method="post" >
<div class="form-group">
<label>Research Title</label>
<input type="text" id="title" name="newTitle" class="form-control" placeholder="Enter title" value="<?php echo $rows[1]; ?>"/>
<input type="hidden" id="id" name="id" class="form-control" placeholder="Enter title" value="<? echo $rows[0]; ?>"/>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="description" name="description" class="form-control" rows="3"></textarea>
</div>
<button id="submit" name="submit" type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
<script src="assets/plugins/jquery-1.10.2.js"></script>
<script src="assets/plugins/bootstrap/bootstrap.min.js"></script>
<script src="assets/plugins/metisMenu/jquery.metisMenu.js"></script>
<script src="assets/plugins/pace/pace.js"></script>
<script src="assets/scripts/siminta.js"></script>
<script src="assets/plugins/morris/raphael-2.1.0.min.js"></script>
<script src="assets/plugins/morris/morris.js"></script>
<script src="assets/scripts/dashboard-demo.js"></script>
</body>
</html>
Why give warning Undefined variable rows when i am defined variable in top of code
Why give warning Undefined variable rows when i am defined variable in top of code
Why give warning Undefined variable rows when i am defined variable in top of code
There are some issues with your code.
mysql_* functions are deprecated and insecure. Please use PDO.
Read the following topic about MySQL injections: How can I prevent SQL injection in PHP?
Don't mix HTML5 and XHTML.
Don't use PHP short open tags <?, use the full tag: <?php
<input type="text" id="title" name="newTitle" class="form-control" placeholder="Enter title" value="<?php echo $rows[1]; ?>"/>
<input type="hidden" id="id" name="id" class="form-control" placeholder="Enter title" value="<? echo $rows[0]; ?>"/>
Instead of <?php echo $rows[0]; ?> use:
<?php echo ( isset ( $rows[0] ) ? $rows[0] : '' ); ?>
Same goes for <?php echo $rows[1]; ?>:
<?php echo ( isset ( $rows[1] ) ? $rows[1] : '' ); ?>
So the complete code would be:
<input type="text" id="title" name="newTitle" class="form-control" placeholder="Enter title" value="<?php echo ( isset ( $rows ) ? $rows[1] : '' ); ?>">
<input type="hidden" id="id" name="id" class="form-control" placeholder="Enter title" value="<?php echo ( isset ( $rows ) ? $rows[0] : '' ); ?>">
you are defining variable $rows in "if" block and because of that $rows is not available in whole document.
Try the below code.
// declare $rows at global level
$rows=null;
if(isset($_GET['ID'])){
$id=$_GET['ID'];
$sql="SELECT * FROM research_tab WHERE ID='$id'";
$result=mysql_query($sql);
// assign value
$rows=mysql_fetch_array($result);
}
Try Below Code:
if(isset($_GET['ID'])){
$id = $_GET['ID'];
$result = $conn->query("SELECT * FROM leads WHERE LeadId='$id'");
$rows = $result->fetch_row();
}
OK catch some problems and i fixit for you in PHP tags:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chemistry_web";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Test if your ID IS a Int if is that you put in your DB
if(isset($_GET['ID']) AND is_numeric($_GET['ID'])){
$id=$_GET['ID'];
$sql="SELECT * FROM research_tab WHERE ID='".$id."'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);}
//include_once 'connection.php';
// if (isset($_GET['ID'])){
// $id=$_GET['ID'];
// $query = "SELECT * FROM $tbl_name WHERE id='$id'";
// $result = mysql_query($query);
// $row = mysql_fetch_array($result);
// }
?>
Just replace your Php tags. May this help you!!
Related
I'm trying to get the select tag to show the titles of the posts that are in the DB so i can select them individually and up date them instead of updating all the titles with the same name.
So my problem is that i can't get it to work and maybe someone may be able to help me.
This is what i mean->https://imgur.com/a/ie1g4hF
if you want the full version you can get it from my github:
https://github.com/TwistedZebra/blog
That version up there does not contain the select tags but uses a text box to delete the post that is named but with a disadvantage of deleten every post named the same.
<?php
require 'config.php';
if (isset($_POST['submit'])) {
$updatetitle = $_POST['updatetitle'];
$title = $_POST['title'];
$content = $_POST['content'];
if (empty($title) || empty($content)) {
header('Location: update.php?=error');
exit();
} else {
$updatedcontent = $connection->prepare('UPDATE posts SET title = :title , content = :content WHERE title = :updatetitle');
$updatedcontent->execute(['title' => $title, 'content'=> $content, 'updatetitle' => $updatetitle]);
header('Location: update.php?=success');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="public/css/main.css">
<title>Control panel</title>
</head>
<body>
<div class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="navbar-brand ">
<h2>BloggerWorld</h2>
</div>
<ul class="nav">
<li class="nav-item">
<a class="nav-link" href="public/index.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="public/posts.php">Posts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="adminpanel.php">Admin Panel</a>
</li>
</ul>
</div>
<br><br><br><br><br><br><br>
<div class="container-fluid">
<div class="container">
<h1>Update post</h1>
<form method="post" action="update.php" >
<select name="delTitle" class="form-control">
<?php foreach ($updatedcontent as $update) { ?>
<option><?php echo $post['title']; ?></option>;
<?php } ?>
</select>
<br>
<input type="text" name="title" class="form-control" placeholder="New title" >
<br>
<textarea name="content" rows="5" cols="60" class="form-control" placeholder="Enter post"></textarea>
<br>
<br>
<button type="submit" name="submit" class="btn btn-success">Update post</button>
</form>
</div>
</div>
<script>
document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] +
':35729/livereload.js?snipver=1"></' + 'script>')
</script> enter code here
</body>
</html>
Why, if I enter a valid username and password, does it work, but when I enter a fake password it doesn't work? Below is my script.
Sign-In.html:
<!DOCTYPE html>
<html lang="">
<head>
<title>LOG-IN</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="../layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
</head>
<body id="top">
<div class="wrapper row1">
<header id="header" class="hoc clear">
<h1>Melis & Morganti</h1>
<p>Hardware Information</p>
</header>
</div>
<div class="wrapper row4">
<nav id="mainav" class="hoc clear">
<ul class="clear">
<li class="active">Home</li>
<li><a class="drop" href="#">ACCOUNT</a>
<ul>
<li>LOG-IN</li>
<li>REGISTER</li>
</ul>
</ul>
</nav>
</div>
<div class="wrapper bgded overlay" style="background-image:url('../images/demo/backgrounds/login.jpg');">
<section id="breadcrumb" class="hoc clear">
<ul>
<li>Home</li>
<li>LOG-IN</li>
</ul>
<h6 class="heading">LOG-IN</h6>
</section>
</div>
<div class="wrapper row3">
<main class="hoc container clear">
<div class="content">
<div id="gallery">
<figure>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%"><legend>Inserisci i tuoi dati</legend>
<form method="POST" action="connectivity.php">
Utente <br><input type="text" name="user" size="40"><br>
Password <br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
</fieldset>
</div>
</body>
</figure>
</div>
</div>
<div class="clear"></div>
</main>
</div>
<div class="wrapper row4">
<footer id="footer" class="hoc clear">
<div class="one_third first">
<h6 class="heading">Sede Legale</h6>
<ul class="nospace btmspace-30 linklist contact">
<li><i class="fa fa-map-marker"></i>
<address>
Via Teano
</address>
</li>
<li><i class="fa fa-phone"></i> +00 0612345678</li>
<li><i class="fa fa-envelope-o"></i> infohardware#MelisMorganti.com</li>
</ul>
</div>
<div class="one_third">
<h6 class="heading"> </h6>
<ul class="nospace linklist">
</ul>
</div>
<div class="one_third">
<h6 class="heading">Newsgroup</h6>
<p class="nospace btmspace-30">Ricevi aggiornamenti</p>
<form method="post" action="#">
<fieldset>
<legend>Newsletter:</legend>
<input class="btmspace-15" type="text" value="" placeholder="Name">
<input class="btmspace-15" type="text" value="" placeholder="Email">
<button type="submit" value="submit">INVIO</button>
</fieldset>
</form>
</div>
</footer>
</div>
<div class="wrapper row5">
<div id="copyright" class="hoc clear">
<p class="fl_left">Copyright © 2017 - All Rights Reserved - Melis - Morganti: Hardware Information</p>
</div>
</div>
<a id="backtotop" href="#top"><i class="fa fa-chevron-up"></i></a>
<!-- JAVASCRIPTS -->
<script src="layout/scripts/jquery.min.js"></script>
<script src="layout/scripts/jquery.backtotop.js"></script>
<script src="layout/scripts/jquery.mobilemenu.js"></script>
</body>
</html>
And this is the connectivity.php:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
define('DB_HOST', 'localhost');
define('DB_NAME', 'login');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Impossibile connettersi: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Impossibile connettersi: " . mysql_error());
/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn() {
session_start();
//starting the session for user profile page
if(!empty($_POST['user']))
{
$query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) AND !empty($row['pass']))
{
$_SESSION['userName'] = $row['pass'];
echo "Sei loggato con successo";
echo "<script> window.location.assign('index_success.html'); </script>";
}
else
{
echo "ID o password sbagliata";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
Why doesn't it work? I tried to use header(), but it doesn't work.
When I use a real username and password, it works: it shows "Sei loggato con successo" for 0.1 milliseconds and it redirects me to "index_success.html". But when I use a fake username or fake password, it sends me to "connectivity.php" without a message or error. It is blank!
WARNING: Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe!
DANGER: Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
Here is how to fix your problem using the mysql_* API with proper hashing of the password:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
define('DB_HOST', 'localhost');
define('DB_NAME', 'login');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Impossibile connettersi: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Impossibile connettersi: " . mysql_error());
session_start();
function SignIn($user, $pw) {
$user = mysql_real_escape_string($user);
$query = mysql_query("SELECT * FROM UserName where userName = '{$user}'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row))
{
if(password_verify($pw, $row['pass']))
{
$_SESSION['userName'] = $row['user'];
echo "Sei loggato con successo";
echo "<script> window.location.assign('index_success.html'); </script>";
}
else
{
echo "ID o password sbagliata";
}
}
else
{
echo "There is a problem";
}
}
if(isset($_POST['submit']))
{
SignIn($_POST['user'], $_POST['pass']);
}
?>
In this code I have used PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. It is not necessary to escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.
hello i am new in php and im trying to print some values from my sql table to an article in html i use article because this is the structure i need . as you will see bellow i basically want to take the path and the username from my sql table and print them to my article any suggestions?
<html >
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Corporate 1</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/custom.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Logo and responsive toggle -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon-fire"></span>
Logo
</a>
</div>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="navbar">
<ul class="nav navbar-nav">
<li class="active">
Home
</li>
<li>
About
</li>
<li>
Products
</li>
<li class="dropdown">
Services <span class="caret"></span>
<ul class="dropdown-menu" aria-labelledby="about-us">
<li>Engage</li>
<li>Pontificate</li>
<li>Synergize</li>
</ul>
</li>
</ul>
<!-- Search -->
<form class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="form-control">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<div class="jumbotron feature">
<div class="container">
<h1><span class="glyphicon glyphicon-equalizer"></span><font color="#F0FFFF" style="Impact">Welcome to Aegean Community</font></h1>
<p><font color="#E9967A">Community for hope</font></p>
<p><a class="btn btn-default" href="LogIn.php">Engage Now</a></p>
</div>
</div>
<!-- Content -->
<div class="container">
<!-- Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Superior Collaboration
<small>Visualize Quality</small>
</h1>
<p>Proactively envisioned multimedia based expertise and cross-media growth strategies. Seamlessly visualize quality intellectual capital without superior collaboration and idea-sharing. Holistically pontificate installed base portals after maintainable products.</p>
</div>
</div>
<!-- /.row -->
<!-- Feature Row -->
<div class="row">
<!-- Feature Row -->
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "some";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM information order by Ranking desc LIMIT 3 ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
?>
<article class="col-md-4 article-intro">
<a href="#">
<img class="img-responsive img-rounded" src=" <?php echo $row['imgagePath'] ?>" alt="">
</a>
<h3>
<?php echo $row['username'] ?>
</h3>
</article>
<?php
}
?>
</div>
</div>
</body>
</html>
You need to use echo $row['var'] to tell PHP to insert that value on the page as a string.
Just change:
<?php $row['imgagePath'] ?>
to
<?php echo $row['imgagePath']; ?>
and
<?php $row['username'] ?>
to
<?php echo $row['username']; ?>
That should be about all you need to do
The major error here is not using an outputting the collected data per $row using echo and you're also missing the semicolon ;.
So changing <?php $row['username'] ?> to <?php echo $row['username'] ?> and <?php $row['imgagePath'] ?> to <?php echo $row['imgagePath']; ?> should do the trick, I believe that's major error you're encountering.
Also instead of using while ($row = $result->fetch_assoc()) { you're better off using while ($row = $result->fetch_assoc()): then you can simply replace the closing bracket } with endwhile;. The same goes for if (expr): and endif;.
Altogether it should look something like this:
<!-- Feature Row -->
<div class="row">
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "some";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM information order by Ranking desc LIMIT 3 ";
$result = $conn->query($sql);
if ($result->num_rows > 0):
// output data of each row
while ($row = $result->fetch_assoc()):
?>
</article>
<article class="col-md-4 article-intro">
<a href="#">
<img class="img-responsive img-rounded" src=" <?php echo $row['imgagePath']; ?>" alt="">
</a>
<h3>
<?php echo $row['username']; ?>
</h3>
</article>
<?php endwhile; ?>
</div>
...
<?php endif; ?>
You should use echo before the variable that you want to print to HTML.
src=" <?php $row['imgagePath'] ?>"
should become
src=" <?php echo $row['imgagePath']; ?>"
I am having serious problems with my product details not updating. It fetches all the product information when I click edit but when I press the submit button to update the product details it does not have an affect on the database. I have been spending quite some time on this and have looked at solutions online as well. None of them seem to work
Here is my code :
<?php
include("functions/mysqli_connect.php");
if(isset($_GET['edit'])) {
$get_id = $_GET['edit'];
$get_pro = "select * from shop where product_id='$get_id'";
$run_pro = mysqli_query($con, $get_pro);
$row_pro=mysqli_fetch_array($run_pro);
$pro_id = $row_pro['product_id'];
$pro_name = $row_pro['name'];
$pro_cat = $row_pro['category'];
$pro_description = $row_pro['description'];
$pro_quantity = $row_pro['quantity'];
$pro_price = $row_pro['price'];
$image = $row_pro['images'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>SB Admin - Bootstrap Admin Template</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/sb-admin.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">SB Admin</a>
</div>
<!-- Top Menu Items -->
<ul class="nav navbar-right top-nav">
<li class="dropdown">
<i class="fa fa-user"></i> <?php echo $_SESSION['admin_username']; ?> <b class="caret"></b>
<ul class="dropdown-menu">
<li>
<i class="fa fa-fw fa-power-off"></i> Log Out
</li>
</ul>
</li>
</ul>
<!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li class="active">
<i class="fa fa-fw fa-dashboard"></i> Insert Products
</li>
<li>
<i class="fa fa-fw fa-table"></i> View Products
</li>
<li>
<i class="fa fa-fw fa-bar-chart-o"></i> Edit Products
</li>
<li>
<i class="fa fa-fw fa-table"></i> Delete Products
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</nav>
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-6">
<form action="edit_pro.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Product Name</label>
<input type="text" class="form-control" id="name" name="name" value="<?php echo $pro_name;?>" >
</div>
<div class="form-group">
<label for="category">Category</label>
<select type="text" class="form-control" id="category" name="category" >
<option><?php echo $pro_cat;?></option>
<option>Henna</option>
<option>Gliter</option>
<option>Cajeput Oil</option>
<option>Henna Cones</option>
</select>
</div>
<div class="form-group">
<label for="image">Image</label>
<input type="file" id="image" name="image" ><img src="stock_images/<?php echo $image; ?>"width="60" height="60" />
<p class="help-block"></p>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description"><?php echo $pro_description;?></textarea>
</div>
<div class="form-group">
<label for="quantity">Quantity</label>
<input type="number" class="form-control" id="quantity" name="quantity" value="<?php echo $pro_quantity;?>" >
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="number" class="form-control" id="price" name="price" value="<?php echo $pro_price;?>" >
</div>
<div class="form-group">
<input name="id" type="hidden" id="id" value="<? echo $pro_id; ?>">
</div>
<input type="submit" name="update" class="btn btn-default" value="Add Stock"></a>.
</form>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
<?php
if(isset($_POST['update'])){
//getting the text data from the form
$id=mysql_real_escape_string($_GET['product_id']);
$update_id = $pro_id;
$pro_name = $_POST['name'];
$pro_cat = $_POST['category'];
$pro_description = $_POST['description'];
$pro_quantity = $_POST['quantity'];
$pro_price = $_POST['price'];
$image = $_FILES['image'] ['name'];
$image_tmp = $_FILES['image'] ['tmp_name'];
move_uploaded_file($image_tmp, "stock_images/$image");
$servername = "localhost";
$username = "Naina";
$password = "Mhendi2015";
$dbname = "farhanaina";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE shop SET name='$pro_name', category='$pro_cat', images='$image', description='$pro_description', quantity='$pro_quantity', price='$pro_price' WHERE product_id='$id'";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
You're using PDO and a prepared statement here. You can't feed a ready SQL query with the variable values into PDO::prepare. Quoting an example from the manual:
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
The array you pass into your PDO::execute will replace each ? with a value in order of the values in the array. Otherwise, you can pass in an associative array and do it with named parameters:
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
Update as of 23rd June 2015
The update query still not working. Took an advice from Rene Kross and made some code cleanup and stumbled upon a few part missing semicolons and etc however the update query are still not working.
Here's the adminUpdate.php
<?php
require 'Connect.php';
$staffID = null;
if ( !empty($_GET['staffID'])) {
$staffID = $_REQUEST['staffID'];
}
if ( null==$staffID ) {
header("Location: ManageAdministrator.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$adminNameError = null;
$emailError = null;
$SKGError = null;
$ExtnError = null;
// keep track post values
$adminName = $_POST['adminName'];
$email = $_POST['email'];
$SKG = $_POST['SKG'];
$Extn = $_POST['Extn'];
// validate input
$valid = true;
if (empty($adminName)){
$adminNameError = "Please enter Administrator Name";
$valid = false;
}
if (empty($email)) {
$emailError = 'Please enter Email Address';
$valid = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Please enter a valid Email Address';
$valid = false;
}
if (empty($SKG)) {
$SKGError = 'Please choose SKG';
$valid = false;
}
if(empty($Extn)){
$ExtnError = "Please enter Extension Number";
$valid = false;
}
// update data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE admin set adminName ='$adminName', email ='$email', SKG ='$SKG', Extn ='$Extn' WHERE staffID = '$staffID'";
$q = $pdo->prepare($sql);
$q->execute(array($staffID,$adminName,$email,$SKG,$Extn));
Database::disconnect();
header("Location: ManageAdministrator.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM admin where staffID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($staffID));
$data = $q->fetch(PDO::FETCH_ASSOC);
$adminName = $data['adminName'];
$email = $data['email'];
$SKG = $data['SKG'];
$Extn = $data['Extn'];
$password = $data['password'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Update Administrator</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Capability Management">
<!-- CSS External Link -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/sb-admin.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<div id="wrapper">
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="HomePage.php"><b> Training Log Database </b></a>
</div>
<ul class="nav navbar-right top-nav">
<li class="dropdown">
<!-- PHP REFER LOGIN NAME-->
<i class="fa fa-user"></i> M Farhan M Fazli <b class="caret"></b>
<ul class="dropdown-menu">
<li>
<i class="fa fa-fw fa-user"></i> Profile
</li>
<li class="divider"></li>
<li>
<!-- PHP LOGOUT FUNCTION -->
<i class="fa fa-fw fa-power-off"></i> Log Out
</li>
</ul>
</li>
</ul>
<!-- Sidebar Menu Items start here -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li>
<i class="fa fa-fw fa-dashboard"></i> Home
</li>
<li>
<i class="fa fa-fw fa-bar-chart-o"></i> Manage Administrator
</li>
<li>
<!-- Add new pages here -->
<i class="fa fa-fw fa-bar-chart-o"></i> Manage Staff
</li>
<li>
<i class="fa fa-fw fa-edit"></i> Manage Training<i class="fa fa-fw fa-caret-down"></i>
<ul id="demo" class="collapse">
<li>
Training Information
</li>
<li>
TBA
</li>
</ul>
</li>
<li>
<i class="glyphicon glyphicon-wrench"></i> Tools for Administrator<i class="fa fa-fw fa-caret-down"></i>
<ul id="demo1" class="collapse">
<li> Add News </li>
<li> Add Announcement </li>
<li> Search News </li>
<li> Search Announcement </li>
<li> View My Post </li>
</ul>
</li>
<li>
<i class="glyphicon glyphicon-info-sign"></i> About
</li>
<li>
<i class="glyphicon glyphicon-question-sign"></i> FAQs
</li>
</div>
<!-- /.navbar-collapse -->
</nav>
<div id="page-wrapper">
<div class="container-fluid">
<div class="row col-lg-12">
<h2 class="page-header"> Update Administrator Account </h2>
<div class="row col-lg-12">
<h3> Administrator details </h3>
<div class="row col-lg-12">
<form class="form-horizontal form-group" action="adminUpdate.php?id=<?php echo $staffID?>" method="post">
<!-- <div class="form-group col-lg-12 <?php echo !empty($staffIDError)?'error':'';?>">
<label>Administrator Staff ID</label>
<input class="form-control" name="staffID" type="text" value="<?php echo !empty($staffID)?$staffID:'';?>">
<?php if (!empty($staffIDError)): ?>
<span class="help-inline"><?php echo $staffIDError;?></span>
<?php endif; ?>
</div>-->
<div class="form-group col-lg-12 <?php echo !empty($adminNameError)?'error':'';?>">
<label>Administrator Name</label>
<input class="form-control" name="adminName" type="text" value="<?php echo !empty($adminName)?$adminName:'';?>">
<?php if (!empty($adminNameError)): ?>
<span class="help-inline"><?php echo $adminNameError;?></span>
<?php endif; ?>
</div>
<div class="form-group col-lg-12 <?php echo !empty($emailError)?'error':'';?>">
<label>Administrator Email</label>
<input class="form-control" name="email" type="text" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-inline"><?php echo $emailError;?></span>
<?php endif; ?>
</div>
<div class="form-group col-lg-12 <?php echo !empty($ExtnError)?'error':'';?>">
<label> Extension Number </label>
<input class="form-control" name="Extn" type="text" value="<?php echo !empty($Extn)?$Extn:'';?>">
<?php if (!empty($ExtnError)): ?>
<span class="help-inline"><?php echo $ExtnError;?></span>
<?php endif; ?>
</label>
</div>
<div class="form-group col-lg-12 <?php echo !empty($SKGError)?'error':'';?>">
<label>SKG</label>
<select class="form-control" name="SKG" value="<?php echo !empty($SKG)?$SKG:'';?>">
<option> SKG 09 </option>
<option> SKG 18 </option>
<option> SKG 20 </option>
<option> SKG 16 </option>
<option> SKG 11 </option>
<option> SKG 13 </option>
<option> SKG 14 </option>
<option> SKG 12 </option>
<option> SKG 15 </option>
<option> SKG 10 </option>
<option> SKG 25 </option>
</select>
<?php if (!empty($SKGError)): ?>
<span class="help-inline"><?php echo $SKGError;?></span>
<?php endif; ?>
</div>
<!-- <div class="form-group col-lg-12 <?php echo !empty($passwordError)?'error':'';?>">
<label>Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password" value="<?php echo !empty($password)?$password:'';?>">
<?php if (!empty($passwordError)): ?>
<span class="help-inline"><?php echo $passwordError;?></span>
<?php endif; ?> -->
</div>
<div class="form-actions col-lg-12">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn btn-default" href="ManageAdministrator.php">Back</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div><!--wrap-->
</body>
</html>
Here's the Connect.php
<?php
class Database
{
private static $dbName = 'tlad' ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'root';
private static $dbUserPassword = '';
private static $cont = null;
public function __construct() {
exit('Init function is not allowed');
}
public static function connect()
{
// One connection through whole application
if ( null == self::$cont )
{
try
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
?>
Here's my table:
As I mentioned earlier, the read, create and delete function are working except for this update function aren't.
Please note: I've followed a tutorial on creating a CRUD datatable, while his template worked but my code aren't. Here's the tutorial's code for update template:
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$emailError = null;
$mobileError = null;
// keep track post values
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($email)) {
$emailError = 'Please enter Email Address';
$valid = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Please enter a valid Email Address';
$valid = false;
}
if (empty($mobile)) {
$mobileError = 'Please enter Mobile Number';
$valid = false;
}
// update data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE customers set name = ?, email = ?, mobile =? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$mobile,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM customers where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$email = $data['email'];
$mobile = $data['mobile'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update a Customer</h3>
</div>
<form class="form-horizontal" action="update.php?id=<?php echo $id?>" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($emailError)?'error':'';?>">
<label class="control-label">Email Address</label>
<div class="controls">
<input name="email" type="text" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-inline"><?php echo $emailError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($mobileError)?'error':'';?>">
<label class="control-label">Mobile Number</label>
<div class="controls">
<input name="mobile" type="text" value="<?php echo !empty($mobile)?$mobile:'';?>">
<?php if (!empty($mobileError)): ?>
<span class="help-inline"><?php echo $mobileError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Your execute has 5 parameters, but query wants 6.
$sql = "UPDATE admin set staffID = ?, adminName = ?, email = ?, SKG = ?, Extn = ? WHERE staffID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($staffID, $adminName, $email, $SKG, $Extn, $staffID));
Also were missing $ in front of email, SKG and Extn.