Data can not be inserted to the table - php

I have a db.php file which connection is established here to the database
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "aigsonlinedb";
$con = new mysqli($host,$user,$pass,$db_name);
function formatDate($date){
return date('g:i a', strtotime($date));
}
?>
"Index.php" file here is a form where the data should be sent and retrieved from the database
<?php
include 'db.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Chat System in PHP</title>
<link rel="stylesheet" href="style.css" media="all"/>
<script>
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.getElementById('chat').innerHTML = req.responseText;
}
}
req.open('GET','chat.php',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
</head>
<body onload="ajax();">
<div id="container">
<div id="chat_box">
<div id="chat"></div>
</div>
<form method="POST" action="index.php">
<input type="text" name="name" placeholder="enter name"/>
<textarea name="msg" placeholder="enter message"></textarea>
<input type="submit" name="submit" value="Send it"/>
</form>
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$msg = $_POST['msg'];
$query = "INSERT INTO chat (name,msg) VALUES ($name','$msg')";
$run = $con->query($query);
if($run){
echo "<embed loop='false' src='chat.wav' hidden='true' autoplay='true'/>";
}
}
?>
</div>
</body>
</html>
chat.php where the data is fetched from the database
<?php
include 'db.php';
$query = "SELECT * FROM chat ORDER BY id DESC";
$run = $con->query($query);
while($row = $run->fetch_array()) :
?>
<div id="chat_data">
<span style="color:green;"><?php echo $row['name']; ?></span> :
<span style="color:brown;"><?php echo $row['msg']; ?></span>
<span style="float:right;"><?php echo formatDate($row['date']); ?></span>
</div>
<?php endwhile;?>
The only problem is the data can not be sent to the database.

In the end of String ; vor SQL Statements. And PHP variables in double quotes and extra double quotes in values for define the datatype of sql

Related

Problem in if and {endif} and {endwhile} in my first Project?

This problem in php I need solution in this day
Please for my homework
Can you help me in my homework please because I'm not working but I'm reading in my university Please can you solve this problem.
Can you explain to my this problem or can connection to my desktop to solution this problem or can send explain .
This code
index.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<?php require_once 'process.php'?>
<?php
if(isset ($_SESSION['message']));?>
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
// and this problem !
<?php endif ?>
?>
<div class="contener">
<?php
$mysqli = new mysqli('localhost', 'root', 'rootroot','crudcrud') or die(mysqli_error($mysqli));
$result = $mysqli->query("SELECT * FORM data") or die($mysqli->error);
?>
<div class="row justify-content-center">
<table class="table">
<thead>
<tr>
<th>usernames</th>
<th>Passowrds</th>
<th colspan="2">Action</th>
<tr>
</thead>
</div>
<?php while ($row = $result->fetch_assoc()): ?>
<tr>
<td><?php echo $row ['username'];?></td>
<td><?php echo $row ['password'];?></td>
<td>
<a href="index.php?edit=<?php echo $row ['id']; ?>"
class="btn btn-info">edit</a>
<a hraf="process.php?delete=<?php echo $row ['id']; ?>"
class="btn btn-danger">
</td>
</tr>
//this problem !
<?php endwhile; ?>
</table>
<?php
function pre_r( $arry ){
echo'<pre>';
print_r($array);
echo'</pre>';
}
?>
<div class="col-lg-6 m-auto">
<form action="process.php" method="post">
<input type="hidden" name="id" value=" <?php echo $id ?> "
<br><br><div class="card">
<div class="card-header bg-dark">
<h1 class="text-white text-center"> Insert Operation </h1>
</div><br>
<label> Username: </label>
<input type="text" name="username" class="form-control" value=" <?php echo $username; ?> " placeholder="Enter Your Username"> <br>
<label> Password: </label>
<input type="text" name="password" class="form-control" value=" <?php echo $password; ?> " placeholder="Password"> <br>
<?php
if ($update == true)
?>
<button class="btn btn-info" type="submit" name="update"> update </button>
<?php else: ?>
<button class="btn btn-success" type="submit" name="save"> Submit </button>
// and this problem !
<?php endif; ?>
</div>
</form>
</div>
</div>
</body>
</html>
code
process.php
=======================================================
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', 'rootroot','crudcrud') or
die(mysqli_error($mysqli));
$id = 0;
$update = false;
$username = '';
$password = '';
if (isset ($_POST['save'])){
$usernames = $_POST['username'];
$passwords = $_POST['password'];
$mysqli->query("INSERT INTO data (username, password) VALUES('$username', '$password')") or
die($mysqli->error);
$_SESSION['message'] = "Record has been saved!";
$_SESSION['msg_type'] = "success!";
header('loocation: index.php');
}
if (isset ($_GET['delete'])){
$id = $_GET['delete'];
$mysqli->query("DELETE FROM data WHERE id=$id") or
die($mysqli->error());
SESSION['message'] = "Record has been deleted!";
SESSION['msg_type'] = "denger!";
header('loocation: index.php');
}
if (isset ($_GET['edit'])){
$id = $_GET['edit'];
$update = true;
$result = $mysqli->query("DELETE FROM data WHERE id=$id") or
die($mysqli->error());
if (count($result)==1){
$row = $result->fetch_array();
$username = $row['username'];
$password = $row['password'];
}
}
if (isset($_POST['update'])){
$id = $_POST['id'];
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli->query("UPDATE data SET username='$username', password='$password' WHERE id=$id") or
die($mysqli->error);
$_SESSION['message'] = "Record has been Update!";
$_SESSION['msg_type'] = "warning!";
header('loocation: index.php');
}
This piece is completely wrong:
if(isset ($_SESSION['message']));?> //<-- : not ;
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
//<-- no closing tag
<?php endif ?> //<-- missing ;
Should be:
if(isset ($_SESSION['message'])):?>
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
endif; ?>
It get's pretty ugly when you use a lot of PHP and HTML in the same file, it might be time to look at using a template engine.

Edit/update row with php doesn't work / Undefined variable

There is something wrong with my code :
On the edit page, I want to show the user the previous value in the input box.
But one error I keep getting about the value is the following :
Notice: Undefined variable: gebruikers_naam in C:\xampp\htdocs\website_herkansing\edit_gebruiker.php on line 72
I think there is something wrong with the isset/submit part but I just
can not figure it out..
Here is the code I'm working with
<?php
session_start();
define('DB_NAME', 'ochtendgloren');
$servername = "localhost";
$username = "root";
$password = "";
$db = "ochtendgloren";
$tbl = "members";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit']))
{
$gebruikers_naam = mysqli_real_escape_string($db, $_POST['gebruikers_naam']);
htmlentities($gebruikers_naam);
$id = $_GET['id'];
$query = "UPDATE members
SET gebruikers_naam = '$gebruikers_naam'
WHERE id = '$id' " ;
$result = $conn->query($query);
if($result){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('edit succesvol!')
window.location.href='admin_members.php';
</SCRIPT>");
}
}
?>
<html>
<head>
<link rel="stylesheet" href="boekingsform.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abel">
</head>
<div class="boeken">
<h1>Wijzig hier de gebruiker</h1>
<form action="editrij.php?id=<?= $id ?>" method="post" >
<div class="row">
<div class="col-25">
<label for="gebruikers_naam"> vul hier de nieuwe gebruikers naam in: </label>
</div></div>
<br>
<div class="row">
<div class="col-75">
<input type="text" name="voornaam" required="required" value="<?= $gebruikers_naam['gebruikers_naam'] ?>"/>
</div>
</div>
<br>
<input type="submit" value="submit" name="submit" />
</form>
</div>
</html>
I think the problem is related with your variable usage and name of input box it must be gebruikers_naam
On line :
<input type="text" name="voornaam" required="required" value="<?= $gebruikers_naam['gebruikers_naam'] ?>"/>
You may use $gebruikers_naam only to print the name.
Also you must assign a global variable before before using it in if clause.
Just assign null like $gebruikers_naam = ""; after variables declarations.
You aren't sending the variable gebruikers_naam, but voornaam. This line of code
<input type="text" name="voornaam" required="required" value="<?= $gebruikers_naam['gebruikers_naam'] ?>"/>
Should be
<input type="text" name="gebruikers_naam" required="required" value="<?= $gebruikers_naam['gebruikers_naam'] ?>"/>
Also, because you are using the variables $id and $gebruikers_naam in the form, you should assign them a value before the if clause.
Still not completely sure the 'flow' of your code makes a lot of sense, but following should help a bit:
<?php
session_start();
//define('DB_NAME', 'ochtendgloren'); // not used in your code, commented out
$servername = "localhost";
$username = "root";
$password = "";
$db = "ochtendgloren";
$tbl = "members";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit']))
{
if(isset($_POST['gebruikers_naam']) && !empty($_POST['gebruikers_naam'])) { // added condition: we need a 'gebruikers_naam'
$gebruikers_naam = mysqli_real_escape_string($conn, $_POST['gebruikers_naam']); // changed $db to $conn
// the return value (encoded string) of htmlentities is not used in your code
// so commented it out
//htmlentities($gebruikers_naam);
$id = $_GET['id'];
$query = "UPDATE members
SET gebruikers_naam = '$gebruikers_naam'
WHERE id = '$id' " ;
$result = $conn->query($query);
}
if($result){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('edit succesvol!')
window.location.href='admin_members.php';
</SCRIPT>");
} else { // added else {} statement
echo "<script> alert('Error: could not update the database'); </script>"; // added: error message
}
}
?>
<html>
<head>
<link rel="stylesheet" href="boekingsform.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abel">
</head>
<div class="boeken">
<h1>Wijzig hier de gebruiker</h1>
<form action="editrij.php?id=<?php echo $id; ?>" method="post" > <!-- you need to echo $id and close with ';' - changed: echo $id; -->
<div class="row">
<div class="col-25">
<label for="gebruikers_naam"> vul hier de nieuwe gebruikers naam in: </label>
</div></div>
<br>
<div class="row">
<div class="col-75">
<?php $gebruikers_naam = (isset($gebruikers_naam)) ? $gebruikers_naam : 'N/A'; ?> <!-- added a test to see if $gebruikers_naam is available -->
<input type="text" name="voornaam" required="required" value="<?php echo $gebruikers_naam; ?>"/> <!-- variable is $gebruikers_naam, changed (echo and ';') -->
</div>
</div>
<br>
<input type="submit" value="submit" name="submit" />
</form>
</div>
</html>

Form Submit Not Being Detected By isset

I am trying to detect a form click using if(isset($_POST['appSelecter'])){ however it seems to not be returning true. This might be to do with the fact that my button click returns to the same page which would loose the form data i had just populated. Can someone confirm if my assumption is correct and if so - how would i need to change this?
Thanks
tried to only paste a sample piece of code to not confuse matters - seems i have made things worse - here is the full flow
<?php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!--META-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Client Portal Login</title>
<!--STYLESHEETS-->
<link href="css/style.css" rel="stylesheet" type="text/css" />
<!--SCRIPTS-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<!--Slider-in icons-->
<script type="text/javascript">
$(document).ready(function() {
$(".username").focus(function() {
$(".user-icon").css("left","-48px");
});
$(".username").blur(function() {
$(".user-icon").css("left","0px");
});
$(".password").focus(function() {
$(".pass-icon").css("left","-48px");
});
$(".password").blur(function() {
$(".pass-icon").css("left","0px");
});
});
</script>
</head>
<body>
<!--WRAPPER-->
<div id="wrapper">
<!--SLIDE-IN ICONS-->
<div class="user-icon"></div>
<div class="pass-icon"></div>
<!--END SLIDE-IN ICONS-->
<!--LOGIN FORM-->
<form name="login-form" class="login-form" action="index.php" method="post">
<!--HEADER-->
<div class="header">
<!--TITLE--><h1>Client Portal Login</h1><!--END TITLE-->
<!--DESCRIPTION--><span>Please login to your client portal</span><!--END DESCRIPTION-->
</div>
<!--END HEADER-->
<!--CONTENT-->
<div class="content">
<!--USERNAME--><input name="username" type="text" class="input username" value="Username" onfocus="this.value=''" /><!--END USERNAME-->
<!--PASSWORD--><input name="password" type="password" class="input password" value="Password" onfocus="this.value=''" /><!--END PASSWORD-->
</div>
<!--END CONTENT-->
<!--FOOTER-->
<div class="footer">
<!--LOGIN BUTTON--><input type="submit" name="submit" value="Login" class="button" /><!--END LOGIN BUTTON-->
<!--REGISTER BUTTON--><input type="submit" name="submit" value="Register" class="register" /><!--END REGISTER BUTTON-->
</div>
<!--END FOOTER-->
</form>
<?php
include("application.php");
if(isset($_POST['submit'])){
$username=$_POST["username"];
$password=$_POST["password"];
$userid = logUserIn($username, $password);
if($userid > 0){
$applicationsForUser = getAppInformation($userid);
printUserApplicationSelectionForm($applicationsForUser);
if(isset($_POST['appSelecter'])) {
echo "this is a test message";
}
}
}
function printUserApplicationSelectionForm($applicationsForUser){
echo "<br/>";
echo "<br/>";
echo "<br/>";
echo "<br/>";
foreach ($applicationsForUser as $app) {
?>
<form action="index.php" method="post">
<input type="hidden" name="userid" value="<?php echo $app->getUserid(); ?>">
<input type="hidden" name="name" value="<?php echo $app->getName(); ?>">
<input type="hidden" name="created" value="<?php echo $app->getDateCreated(); ?>">
<input type="hidden" name="invoice" value="<?php echo $app->getInvoice(); ?>">
<input type="hidden" name="comment" value="<?php echo $app->getComment(); ?>">
<input type="submit" name="appSelecter" value="<?php echo $app->getName(); ?>">
</form>
<?php
}
}
function getAppInformation($userid){
$applicationsForUser = array();
$conn = new mysqli('localhost:3306', 'root', '', 'clientportal');
if ($conn->connect_errno > 0) {
die('Could not connect: ' . mysql_error());
}else{
//we have connected to the database
$sql = "SELECT * FROM application WHERE userid = '$userid'";
if(!$val = $conn->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}else{
$index = 0;
while($row = $val->fetch_assoc()){
$userid = $row['userid'];
$name = $row['name'];
$dateCreated = $row['date'];
$invoice = $row['invoiceid'];
$comment = $row['commentsid'];
$application = new Application($userid, $name, $dateCreated, $invoice, $comment);
$applicationsForUser[$index] = $application;
$index++;
}
}
}
$conn -> close();
return $applicationsForUser;
}
function logUserIn($username, $password) {
if(!isset($username) && !isset($password)){
return -1;
}
$result = -1;
//$conn = mysql_connect('localhost', 'web214-admin-ava', 'secondstory');
$conn = new mysqli('localhost:3306', 'root', '', 'clientportal');
if ($conn->connect_errno > 0) {
die('Could not connect: ' . mysql_error());
}else{
//we have connected to the database
$sql = "SELECT * FROM members WHERE username = '$username' AND password = '$password'";
if(!$val = $conn->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}else{
while($row = $val->fetch_assoc()){
$result = $row['id'];
break;
}
}
}
$conn -> close();
return $result;
}
?>
<!--END LOGIN FORM-->
</div>
<!--END WRAPPER-->
<!--GRADIENT--><div class="gradient"></div><!--END GRADIENT-->
</body>
</html>
You have used folowing in the form submit:
onClick="location.href='index.php'" // Making a GET request
This is not submitting the form using POST method. Remove this and it'll work.
Update: There is no submit button with name submit so this condion will not work:
if(isset($_POST['submit']))
Make it:
if(isset($_POST['appSelecter']))
You don't need if(isset($_POST['submit'])) instead use;
if(isset($_POST['appSelecter'])) {
$username=$_POST["username"];
$password=$_POST["password"];
$userid = logUserIn($username, $password);
if($userid > 0){
$applicationsForUser = getAppInformation($userid);
printUserApplicationSelectionForm($applicationsForUser);
}
}
You dont nee this
onClick="location.href='index.php'"
dont do anything , just apply value to button i, i think you have applied already ,
by location.href your request will be send by GET Method in thgis case no form elements sent to the server
if you allow native form submission then all form elements will be sent to server, in case of multiple forms , the only elements sent realted to that submit button form thats it

php can't connect to database, display blank page

so I have this code for my form.
newuser.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900" rel="stylesheet" />
<link href="css/styles.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/fonts.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/newuser.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="page" class="container">
<div id="header">
<div id="logo">
<img src="img/minilogo.jpg" alt="" />
<h1>ADMIN</h1>
<span>PERMOHONAN DATA</span>
</div>
<div id="menu">
<ul>
<li class=""><a href="admin.php" >Home</a></li>
<li><a href="new.php" >USER</a></li>
<li><a href="#" >PENYEDIA</a></li>
<li><a href="#" >UPDATE</a></li>
<li><a href="logout.php" >LOG OUT</a></li>
</ul>
</div>
</div>
<div id="main">
<div id="banner">
<img src="img/pic01.jpg" alt="" class="image-full" />
<div id="welcome">Pendaftaran User Baru.
</div>
<div class="title">
<!--untuk form-->
<form class="form" action="submitnew.php" method="post" name="form" >
<ul><li>
</li>
</li>
<li>
<label for="name">Nama :</label>
<input type="text" name="name" required />
</li>
<li>
<label for="tel">No. Telefon:</label>
<input type="text" name="tel" required />
</li>
<li>
<label for="email">E-mail:</label>
<input type="email" name="email" placeholder="name#something.com" required />
<class="form_hint"> <script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>
</li>
<li>
<label for="username">Username:</label>
<input type="text" name="username" required />
</li>
<li>
<label for="password">Password:</label>
<input type="password" name="password" required />
<!--<li>
<label for="admin">Admin</label>
<input id="radio1" name="admin" type="radio" class="radio-btn" value="admin" />
</li>-->
<li>
<button class="submit" type="submit">Create</button>
</li>
</ul>
</form>
</body>
</html>
the data will be pass through this,
submitnew.php
<?php
//debug mode
error_reporting(E_ALL);
ini_set('display_errors', '1');
//to show some error is smthng went wrong
$errors = array();
//connect to DB
$connection = mysql_connect('localhost','root','');
$db = mysql_select_db('permohonan_data',$connection);
//will run if user did submit the form
if (!empty($_POST)){
//connect sql server:
$name = $_POST['name'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
//no error til here
if (empty($error)){
//prevent SQL injection
$name = mysql_real_escape_string($name);
$tel = mysql_real_escape_string($tel);
$email = mysql_real_escape_string($email);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
}
//try insert value
$query = "INSERT INTO admin
(name,tel,email,username,password)
VALUES ('$name', '$tel', '$email', '$username', '$password)";
//try
if (!mysql_query($query)){
//
//die(mysql_error());
$errors[] = "Can't insert the values";
}
else {
//on success
header("Location:new.php");
exit();
}
}
?>
the problem is, it won't connect to the database neither redirect to the new.php. it will only display blank page. did I code wrong?
you have error in query(missed the ending quotes in password ):
$query = "INSERT INTO admin
(name,tel,email,username,password)
VALUES ('$name', '$tel', '$email', '$username', '$password)";
should be:
$query = "INSERT INTO admin
(name,tel,email,username,password)
VALUES ('$name', '$tel', '$email', '$username', '$password')";
and replace this:
if (empty($error)){
by
if (empty(mysql_error())){
for checking mysql error.
and instead of:
//connect to DB
$connection = mysql_connect('localhost','root','');
$db = mysql_select_db('permohonan_data',$connection);
try this:
//connect to DB
$connection = mysql_connect('localhost','root','') or die(mysql_error());
$db = mysql_select_db('permohonan_data',$connection) or die(mysql_error());
Problem is, you are using:
$errors = array();
and $error never gets a value in your code so no query executed :-)
Use this and let me know:
<?php
//debug mode
error_reporting(E_ALL);
ini_set('display_errors', '1');
//connect to DB
$connection = mysql_connect('localhost','root','');
mysql_select_db('permohonan_data',$connection);
//will run if user did submit the form
if (!empty($_POST)){
//connect sql server:
$name = $_POST['name'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
//prevent SQL injection
$name = mysql_real_escape_string($name);
$tel = mysql_real_escape_string($tel);
$email = mysql_real_escape_string($email);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$result = mysql_query("INSERT INTO admin (name,tel,email,username,password)
VALUES ('$name', '$tel', '$email', '$username', '$password)");
if (!empty($result)) {
// check for empty result
if (mysql_affected_rows() > 0) {
$response = $result;
$response["success"] = 0;
$response["message"] = "One row effected";
// echoing JSON response
echo json_encode($response);
} else {
// No profile found
$response["success"] = 1;
$response["message"] = "No row effected";
// echo no users JSON
echo json_encode($response);
}
} else {
// No profile found
$response["success"] = 2;
$response["message"] = "No row effected";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = -1;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

SQL update query not cooperating

I am adding a save/update button to the bottom of my editing form on my admin panel. For some reason, whenever I make a change to the form and click save it just reloads the page with no changes made. I also noticed that ONLY when I try to run the code from the pages.php file(runnning from index then clicking pages is fine) it says:
Undefined variable: dbc in
C:\Users\Jake\Desktop\Xampp\htdocs\jakefordsite\admin\content\pages.php
on line 12
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in
C:\Users\Jake\Desktop\Xampp\htdocs\jakefordsite\admin\content\pages.php
on line 12
I can get rid of this error by declaring a new $dbc(databaseconnection) variable in pages.php, but I still have the same problem updating my form data.
PAGES.PHP:
<?php ## Page Manager ?>
<h2>Page Manager</h2>
<div class="col sidebar">
<ul>
<?php
$q = "SELECT * FROM pages ORDER BY name ASC";
$r = mysqli_query($dbc, $q);
if ($r)
{
while ($link = mysqli_fetch_assoc($r))
{
echo '<li>'.$link['name'].'</li>';
}
}
?>
</ul>
</div>
<div class="col editor">
<?php
if (isset($_POST['submitted']) == 1) {
$q = "UPDATE pages SET title='$_POST[title]', name='$_POST[name]', body='$_POST[body]', WHERE id = '$_POST[id]'";
$r = mysqli_query($dbc, $q);
}
if (isset($_GET['id'])) {
$q = "SELECT * FROM pages WHERE id = '$_GET[id]' LIMIT 1";
;
$r = mysqli_query($dbc, $q);
$opened = mysqli_fetch_assoc($r);
?>
<form action="?page=pages&id=<?php echo $opened['id'] ?>" method="post">
<p><label>Page title: </label><input type="text" size="30" name="title" value="<?php echo $opened['title']?>"></p>
<p><label>Page name:</label> <input type="text" size="30" name="name" value="<?php echo $opened['name']?>"></p>
<label>Page body: </label><br>
<textarea name="body" cols="30" rows="8"><?php echo $opened['body'] ?></textarea>
<input type="hidden" name="submitted" value="1"/>
<input type="hidden" name="id" value="<?php echo $opened['id'] ?>"/>
<p><input type="submit" name="submit" value="Save Changes"/></p>
</form>
<?php } ?>
</div>
INDEX.PHP:
<?php
// Setup document:
include('config/setup.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php //echo $page_title; ?>JakeForDesign - Admin Panel</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="header"> <?php head(); ?> </div>
<div class="nav_main"> <?php nav_main(); ?> </div>
<div class="content"> <?php include('content/'.$pg.'.php'); ?> </div>
<div class="footer"> <?php footer(); ?> </div>
</div>
</body>
</html>
SETUP.PHP
<?php
## Setup Document
// host(or location of the database), username, //password, database name
$dbc = #mysqli_connect('127.0.0.1', 'root', 'password', 'main') OR die ('Could not connect to the database because: '. mysqli_connect_error() );
include('Functions/sandbox.php');
include('Functions/template.php');
if (isset($_GET['page']) == '')
{
$pg = 'home';
}
else
{
$pg = $_GET['page'];
}
$page_title = get_page_title($dbc, $pg);
?>
on Pages.php you have
$r = mysqli_query($dbc, $q);
$q is fine but you have not mentioned $dbc
on your setup page, create a class for connection, declareing a connection method and then, on PAGES.PHP:
$db_obj = new setup(); /* create object for setup class */
$dbc = $db_obj -> connect_db();/* call connection method */

Categories