Update query is not updating data in PHP mysqli (procedural) - php

I am facing issues with id='$id'
SELECT Query is working fine but update query is not working
if I put any id number instead of $id it updates the data but when I use $id it just does nothing.
<?php
$db = mysqli_connect("localhost", "root", "", "aashir");
$id = $_GET['id'];
$query = "SELECT * FROM students WHERE id='$id' ";
$result = mysqli_query($db, $query);
while ($row = mysqli_fetch_array($result)) {
$key = $row['id'];
$name = $row['student_name'];
$fname = $row['father_name'];
$program = $row['student_program'];
}
if (isset($_POST['submit'])) {
$s_name = $_POST['s_name'];
$s_fname = $_POST['s_fname'];
$s_program = $_POST['s_program'];
$query2 = "UPDATE students SET student_name = '$s_name', father_name = '$s_fname', student_program = '$s_program' WHERE id='$id' ";
mysqli_query($db, $query2);
header("Location:show.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Student</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
</head>
<body>
<div class="container mt-5">
<form method="POST" action="edit.php" class="col-lg-6 offset-lg-3">
<h2 class="text-center">Edit a Student</h2>
<div class="form-group">
<input type="text" name="s_name" class="form-control" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<input type="text" name="s_fname" class="form-control" value="<?php echo $fname; ?>">
</div>
<div class="form-group">
<input type="text" name="s_program" class="form-control" value="<?php echo $program; ?>">
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-success" value="Update">
</div>
</form>
</div>
</body>
</html>

you have two options to fix your issue (without talking about SQL injection, already quoted in the comments and to be addressed since it is a huge security risk for your application)
Change the form action to pass the id to the page while processing the form:
action="edit.php?id=<?php echo $id; ?>"
or better add an hidden input with the id:
<input type="hidden" name="id" value="<?php echo $id; ?>">
and then:
if (isset($_POST['submit'])) {
$s_name = $_POST['s_name'];
$s_fname = $_POST['s_fname'];
$s_program = $_POST['s_program'];
$id = $_POST['id'];
in this case the action can remain the same.
Posting the form you are reloading the page and not passing the id anymore via url as at the first load

You're performing the UPDATE using a POST request, yet you're looking for $id as a GET parameter. This way, $id will always be undefined, and thus the query fails.
You can try overloading the form action URL, like so:
<form method="POST" action="edit.php?id=<?php echo $_GET['id']; ?>" class="col-lg-6 offset-lg-3">

Related

$_GET['id'] disappears after I press Edit user button and that's why my query for update is not working

Here's the code from where I am sending id
In this code I am getting ID by using $_GET['id']. At start the $_GET['id'] fetches id and the first query of SQL works to fetch the data in input fields but soon as I press EDIT button to update the data than the data stays same in database. I used echo after isset($_POST['edit_user']) but there is nothing in $id.
<?php
session_start();
include("config.php");
//echo $id=$_SESSION['id'];
$id = isset($_GET['id']) ? $_GET['id'] : '';
$sql = "SELECT * FROM phone WHERE id='$id'";
$res = $conn->query($sql);
$row = $res->fetch_assoc();
echo $n = isset($row['name']) ? $row['name'] : '';
echo $phone = isset($row['contacts']) ? $row['contacts'] : '';
if (isset($_POST['edit_user'])) {
$name = $_POST['fname'];
$number = $_POST['num'];
//var_dump($name);
$sql = "UPDATE phone SET name='$name', contacts='$number' WHERE id='$id'";
//var_dump($sql);
//var_dump($res);
if ($conn->query($sql) == TRUE) {
echo "<script>alert('You have successfuly updated user') </script>";
header("location:index.php");
} else {
echo "<script>alert('Failed to edit user') </script>";
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>EDIT USER</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-12">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4" jumbotron my-5>
<h4 class="text-center my-2">Edit User</h4>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label>Name</label>
<input type="text" name="fname" class="form-control" autocomplete="off" required value="<?php echo $n ?>">
<label>Number</label>
<input type="text" name="num" class="form-control" autocomplete="off" required value="<?php echo $phone ?>">
<input type="submit" name="edit_user" value="Edit User" class="edituser">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Because when you submit its reloading page so you are missing id in the query string, You just need to pass query string to get data from an URL using $_GET.
on your given code you can do this by replacing the action link
$_SERVER["PHP_SELF"]
with
"http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
You can us both $_GET and $_POST at the same time but you have to define the
$_GET parameter in the URI like:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>?id=21">
or use
$_POST with an hidden input type like:
<input type="hidden" id="id" name="id" value="21">
and you got one more error in the code i ansered here
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
How to redirect to page with the location?
This will not work:
echo "<script>alert('You have successfuly updated user') </script>";
header("location:index.php");
If you want to alert a message you have to do the alert after location|load the next side something like:
<?php
if ($conn->query($sql) == TRUE) {
$ok = 1;
}
else{
$ok = 2;
}
header("location:index.php?ok=$ok");
?>
on the new side do:
<?php
$ok = ($_GET['ok'] ?? '');
if($ok === 1){
echo "<script>alert('You have successfuly updated user')";
}
elseif($ok === 2){
echo "<script>alert('Failed to edit user') </script>";
}
?>
Dont forget your code like this is open for injection malicious code
Fix this
since you want to update by using the $_GET['id'], you need to ensure ?id=69 (69 is a dummy id) is present your url when the code runs.
replace your opening form with this:
<form action="./update.php?id=<?=$id?>" method="post">
or:
<form action='<?php echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";?>' method='post'>

Unable to use $_SESSION in an other file (PHP)

Hello good afternoon, I'm having the trouble of not being able to use add a $_POST value to my $_SESSION variable so that I can use it later in my profile file.
I can give it other values like "hello" outside the if and it echoes hello in levraiprofilewesh.php.
I've tried making $_SESSION a super global variable and global but it didn't work.
I've been stuck on it for a few hours :(.
I don't need to upload the website on the web, it's just for local use, so there's no need for privacy feedback although it has helped me for the future.
login.php code:
<?php
session_start();
include("db_connect.php");
if(isset($_POST['login_button'])) {
$user_email = trim($_POST['user_email']);
$user_password = trim($_POST['password']);
$_SESSION['password'] = $user_password;
$usql = "SELECT * FROM users WHERE Email='$user_email' && Password='$user_password'";
$uresult = mysqli_query($db, $usql) or die("database error:". mysqli_error($db));
$urow = mysqli_fetch_assoc($uresult);
//while($row = mysqli_fetch_array($uresult))
//$STPMARCHEFRERE = $row['Firstname'];
//$SESSION = $row['Firstname'];
if($urow['Password']==$user_password){
setcookie("userid",$user_password,time()+(60*60*24*7));
setcookie("useremail",$user_email,time()+(60*60*24*7));
//$GLOBALS['SESSION'] = $user_password;
$time=time();
$queryz = "UPDATE Users
Set Online='Online',
Time='$time'
WHERE Password='$user_password' ";
$db->query($queryz) or die('Errorr, query failed to upload');
echo "ok";
} else {
echo "email or password does not exist."; // wrong details
}
}
?>
levraiprofilewesh.php code:
<?php
session_start();
include("login.php");
$connection = mysqli_connect('localhost', 'root','','phpchart');
if(isset($_SESSION['password'])) {
$username = $_SESSION['password'];
$query = "SELECT *
FROM users
WHERE Password = '%$username%'";
$select_user_profile_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($select_user_profile_query)) {
$post_tamere = $row['Firstname'];
$post_tondaron = $row['Sirname'];
$post_tasoeur = $row['Phone'];
$post_tonneveu = $row['Institution'];
$post_julia = $row['Email'];
}
}
?>
<?php
if(isset($_POST['edit_user'])) {
$user_firstname = $_POST['user_firstname'];
$user_lastname = $_POST['user_lastname'];
$user_role = $_POST['user_role'];
//$post_image = $_FILES['image']['name'];
//$post_image_temp = $_FILES['image']['tmp_name'];
$username = $_POST['username'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
//$post_date = date('d-m-y');
//move_uploaded_file($post_image_temp, "./images/$post_image" );
$query = "SELECT randSalt FROM users";
$select_randsalt_query = mysqli_query($connection, $query);
if(!$select_randsalt_query) {
die("Query Failed" . mysqli_error($connection));
}
$row = mysqli_fetch_array($select_randsalt_query);
$salt = $row['randSalt'];
$hashed_password = crypt($user_password, $salt);
$query = "UPDATE users SET ";
$query .="user_firstname = '{$user_firstname}', ";
$query .="user_lastname = '{$user_lastname}', ";
$query .="user_role = '{$user_role}', ";
$query .="username = '{$username}', ";
$query .="user_email = '{$user_email}', ";
$query .="user_password = '{$hashed_password}' ";
$query .= "WHERE username = '{$username}' ";
$edit_user_query = mysqli_query($connection,$query);
confirmQuery($edit_user_query);
}
?>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<div id="wrapper">
<!-- Navigation -->
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Welcome to Profile
<small>Author</small>
</h1>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Firstname</label>
<input type="text" value="<?php echo $post_tamere; ?>" class="form-control" name="user_firstname">
</div>
<div class="form-group">
<label for="post_status">Lastname</label>
<input type="text" value="<?php echo $post_tondaron; ?>" class="form-control" name="user_lastname">
</div>
<div class="form-group">
<select name="user_role" id="">
<option value="subscriber"><?php echo $user_role; ?></option>
<?php
if($user_role == 'admin') {
echo "<option value='subscriber'>subscriber</option>";
} else {
echo "<option value='admin'>admin</option>";
}
?>
</select>
</div>
<!--<div class="form-group">
<label for="post_image">Post Image</label>
<input type="file" name="image">
</div>-->
<div class="form-group">
<label for="post_tags">Phone</label>
<input type="text" value="<?php echo $post_tasoeur; ?>" class="form-control" name="username">
</div>
<div class="form-group">
<label for="post_content">Email</label>
<input type="email" value="<?php echo $post_tonneveu; ?>" class="form-control" name="user_email">
</div>
<div class="form-group">
<label for="post_content">Password</label>
<input type="password" value="<?php echo $post_julia; ?>" class="form-control" name="user_password">
</div>
<h1><?php echo $_SESSION['superhero']; ?></h1>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="edit_user" value="Update Profile">
</div>
</form>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>

Have a Insert and a Edit button in the same form using PHP and SQL

I've been going at this for a couple of hours now (searching here and google) but nothing I find helped me to get this to work.
I'm trying to make one form and have a Insert INTO and UPDATE $table SET function in the same form, using buttons.
But whatever I try the Update doesn't copy the data from the form. INSERT INTO works. But when I try to edit the form, no data is copied.
HTML:
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<input type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
Update
</div>
</form>
CMS_DATA.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "INSERT INTO $table (ID, Omschrijving, Datum, Tijd, Locatie, Dresscode )
VALUES ('" .$id."','" .$omschrijving."','".$datum."',' ".$item."','".$locatie."','".$dresscode."')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
UPDATE-CMS.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "UPDATE $table SET
Omschrijving = '$omschrijving', Datum = '$datum', Tijd = '$item', Locatie = '$locatie', Dresscode = '$dresscode' WHERE ID = '1'";
if ($conn->query($sql) === TRUE) {
echo "Done";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Like I said, the INSERT INTO works fine. But no data (values) are copied when using the update. I just overrides ID 1 with empty rows... I hope someone can help me... thanks in advance.
You have defined action on your form action="cms_data.php", so your button that is responsible for submitting that form works correctly, but on the other hand you've defined another button (anchor tag), that only has href (hence points to another page), so if you click on it, you won't pass any arguments with it.
My suggestion here is, as I mentioned in comment below your question, to use two buttons, both with submit property, but then handle clicking on them via JavaScript.
When you capture submitment, you can dinamically change action on your form, so your data will be passed to desired script.
Handling multiple buttons in a form:
Process a Form Submit with Multiple Submit Buttons in Javascript
Manipulating form's action property:
How to use JavaScript to change the form action
Another suggestion would be that you use prepared statements in your query, so you wouldn't be vulnerable to SQL injections (from the comments section, I see you'll only be using this locally, but this is a good practice).
Using Mysqli prepared statements:
https://stackoverflow.com/a/24989090/5018750
Echo only prints value on the screen in your respective textbox and does not assign that value to your actual field.
Instead what you can do is start the session in the start of your contact form and store those fields in session variable.
When user selects UPDATE option he will get redirected to UPDATE-CMS.php page. In UPDATE-CMS.php you can retrieve your stored session variables and assign them to your actual variables. In this way you can carry forward your old as well as new values.
anchor just links the page it will not pass data
you are trying to have submit and update button in one form
solution:
in html5 button has formaction attribute .formaction specifies page data to be transferred .so that different button can have different action page
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<buttin formaction="CMS-DATA.php" type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
<button formaction="UPDATE-CMS.php" >Update </button>
</div>
</form>

UPDATE query is not working php

Going to try to keep it short. I have a while loop in grid.php file to fill up a table as such...
<?php while($product = $products->fetch_assoc()) { ?>
<tr>
<td><?php echo $product['cd_id']?></td>
<td><?php echo $product['cd_title']?></td>
<td><?php echo $product['cd_musician_fname']?></td>
<td><?php echo $product['cd_musician_lname']?></td>
<td><?php echo $product['cd_price']?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php } ?>
If I click the first anchor tag takes me to a edit.php file and here is the head code for that file.
<?php include '_includes/db.php';
$cd_id = trim($_GET['id']);
$message = '';
include '_includes/connection.php';
if($db->connect_error){
$message = $db->connect_error;
}else{
$sql = "SELECT * FROM CD WHERE cd_id = $cd_id";
$result = $db->query($sql);
$row = $result->fetch_assoc();
if($db->error){
$message = $db->error;
}
}
?>
Now I will show the html of edit.php
<!-- Product Musician last name-->
<fieldset class="form-group">
<label for="cd_musician_lname">Musician's lirst name</label>
<input type="text" class="form-control" id="cd_musician_lname" name="cd_musician_lname" value="<?php echo $row['cd_musician_lname'];?>">
</fieldset>
<!-- End of Musician last name-->
<!-- Product price-->
<fieldset class="form-group">
<label for="cd_price">Product price</label>
<input type="text" class="form-control" id="cd_price" name="cd_price" value="<?php echo $row['cd_price'];?>">
</fieldset>
<!-- End of Product price-->
<!-- Form submit button-->
Update Record
<a class="btn btn-primary" href="index.php" role="button">Go Back Home</a>
I have the edit.php page working just fine but if I make changes in the fields and click the submit anchor tag I get all the fields of the row empty but the PK. Here is the code for the final edit_confirm.php file
<?php
include '_includes/db.php';
$cd_id = trim($_GET['id']);
$cd_title = $_POST['cd_title'];
$cd_musician_fname = $_POST['cd_musician_fname'];
$cd_musician_lname = $_POST['cd_musician_lname'];
$cd_price = $_POST['cd_price'];
$message = '';
include '_includes/connection.php';
if($db->connect_error){
die("Connection failed: ".$db->connect_error);
} else {
$sql = "UPDATE CD SET cd_title='".$cd_title."', cd_musician_fname='".
$cd_musician_fname."', cd_musician_lname='".
$cd_musician_lname."', cd_price='".$cd_price."' WHERE cd_id = $cd_id ";
$db->query($sql);
var_dump($sql);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php include '_includes/main-head.php';?>
</head>
<body>
<?php include '_includes/main-navbar.php';?>
<div class="container">
<hr>
<?php
if($db->query($sql) === TRUE){ ?>
<h1>Record updated successfully.</h1>
<?php echo $cd_title; ?>
<?php echo $record->affected_rows ?>
<p> record was updated in the database.</p></br>
<?php } else { ?>
<p>Error updating the record: </p> <?php $db->error; ?>
<?php }; ?>
<hr>
<a class="btn btn-primary" href="index.php" role="button">Go Back Home</a>
</div>
<?php include '_includes/main-script.php';?>
</body>
</html>
If you notice in the edit_confirm.php I did a var_dump to see what are the values in the variables and it shows empty.
I need help with this.
Thank you in advance.
Man the better way to do this is make it simple to test if the record is updating or not
formsample.php
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
include("connection.php");
$id = $_GET['id'];
$query= "select * from clients where id = '$id'";
$sql = mysqli_query($connect, $query);
$result = mysqli_fetch_assoc($sql);
?>
<form action="process.php" method="post">
<input type="text" name="name" id="name" value="<?php echo $result['name'] ?>" />
<input type="text" name="email" id="email" value="<?php echo $result['email'] ?>" />
<input type="hidden" name="id" id="id" value="<?php echo $id?>" />
<input type="submit" />
</form>
</body>
</html>
process.php
<?php
include("connection.php");
$id = $_POST['id'];
$name = $_POST['name'];
$email= $_POST['email'];
$query = "UPDATE clients set name= '$name', email ='$email' where id = '$id'";
$sql = mysqli_query($connect, $query);
?>
Update Record
This is not the proper way to submit a form - it won't work at all.
You need to have a form opening and closing tag, the target address is in the action attribute of the form element, and the method is on there too and should be post for this form (method="POST"). In your code you have a link where you should have a submit input so it won't submit the data, it will just redirect you to that URL. You should have something like this:
<input type="submit" value="Update Record" />
http://www.w3schools.com/html/html_forms.asp

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