PHP POST and GET in same statement - php

I've found similar questions, but have been unable to tie them into my example. I am very new to PHP and completely self teaching.
At present I have a form for entering a new customer. In that form I want the user to be able to select an existing DB item (business) and insert that BusinessID into the CUSTOMER table. My problem is that I can GET the BusinessID, but then I can't POST that same ID with the other field inputs. Code below
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>New Contact</title>
<!--Declare CSS and JavaScript-->
<link rel="stylesheet" type="text/css" href="RealtyCRM_Style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery.resmenu.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
$('.toresponsive').ReSmenu();
});
</script>
<!--Begin Header Code-->
<!--Begin Header Code-->
<div class="BodyHeader">
<div>
</div>
</div>
<!--Begin Menu Code-->
<div class="menu_container" style="position:relative; z-index:11;">
<ul class="toresponsive">
<li>Log In</li>
<li>Contact</li>
<li>News</li>
<li class="current-menu-item">Dashboard
<ul>
<li>Add New Data</li>
<li>Update Data</li>
<li>Search</li>
<li>Report</li>
<li>Admin Page</li>
<li>Log Interaction</li>
</ul>
</li>
</ul>
</div>
<br>
<!--Begin Dashboard Buttons Code-->
<div class="DashboardButtonsTop">
<h1 class="centeredDashBoardButtonInactive">New Retailer</h1>
<h1 class="centeredDashBoardButton">New Contact</h1>
<h1 class="centeredDashBoardButtonInactive">New Property</h1>
</div>
<hr style="width:700px; height:5px;">
<br>
<br>
<!--END Dashboard Buttons Code-->
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost';
$dbuser = 'leasingl_dbwrite';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$contactFirstName = addslashes ($_POST['contactFirstName']);
$contactLastName = addslashes ($_POST['contactLastName']);
}
else
{
$contactFirstName = $_POST['contactFirstName'];
$contactLastName = $_POST['contactLastName'];
}
$contactPhoneNumber = $_POST['contactPhoneNumber'];
$contactEmail = $_POST['contactEmail'];
$Business = $_POST['BusinessID'];
$sql = "INSERT INTO Contact ". "(ContactFName,ContactLName, ContactMobilePhone, contactEmail, BusinessID, CreatedDate) ". "VALUES('$contactFirstName','$contactLastName','$contactPhoneNumber', '$contactEmail', '$Business', NOW())";
mysql_select_db('applicationDatabase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "<div style='text-align:center;'>Entered data successfully\n</div>";
echo "<br><div><a href='contactdataentry.php' class='redirectButton'>Add More Contacts</a>\n</div>";
echo "<br><div><a href='dashboard.php' class='redirectButton'>Return to Dashboard</a></div>";
mysql_close($conn);
}
else
{
?>
<div class="Form_container">
<form method="post" action="<?php $_PHP_SELF ?>">
Contact First Name<br>
<input class="largeInput" type="text" name="contactFirstName" ID="contactFirstName"><br>
Contact Last Name<br>
<input class="largeInput" type="text" name="contactLastName" ID="contactLastName"><br>
Contact Phone Number<br>
<input class="largeInput" type="text" name="contactPhoneNumber" placeholder="### - ### - ####" ID="contactPhoneNumber"><br>
Contact Email<br>
<input class="largeInput" type="text" name="contactEmail"><br>
Business<br>
<?php
$servername = "localhost";
$username = "leasingl_dbread";
$password = "password";
$dbname = "applicationDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT RetailerID, RetailerName FROM Retailer ORDER BY RetailerName DESC";
$result = $conn->query($sql);
?>
<select style='text-align:center;' class='largeInput' name='Business' ID='Business'>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='". $row["RetailerID"]. "'>" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option><br><br>";
}
} else {
echo "0 results";
}
?>
</select><br><br>
<?php
$conn->close();
?>
<input name="add" type="submit" id="add" value="Add Contact" class="button">
</form>
<br>
<hr style="width:400px; height:10px;">
</div>
<?php
}
?>
</body>
</html>'
So being able to insert the value from my drop down is the main issue. Additionally, I'm sure there is unnecessary / incorrect code in what I posted, I've been piecing together examples one at a time.
Thank you for all the help, if I can get this working I can have a functioning basic version of my application
EDIT
I have successfully prepopulated my drop down, and the user then chooses from that list. I want to pass that choice via my INSERT statement. I worry that the two different CONNECTIONS which I establish are part of the reason my INSERT won't recognize $Business

It appears you are referring to GET in a confusing way. In PHP there is $_GET and $_POST variables, and when you mention GET in all-caps, in implies you are using $_GET - which in fact you are not.
The solution - as I understand the question - is actually fairly straightforward.
Inside your form, add a hidden input that stores (and then passes) the BusinessID variable, like so:
<input type="hidden" name="BusinessID" value="<?php echo $Business; ?>">
As you mention you are just learning, here's some additional tips:
Name your variables consistently throughout. If the name of the database column is BusinessID, then name your variable $businessID" and your inputBusinessID".
Kudos to you for good indenting / formatting! That will save you gobs of time when troubleshooting / reading your own code!
EDIT
If what you are trying to do is pre-select the record in the dropdown, then alter your loop like so:
while($row = $result->fetch_assoc()) {
// Note: I've removed the <br> tags here, they don't belong in a select dropdown
echo "<option value='". $row["RetailerID"]. "'";
// If the ID matches, make this the selected option
// NOTE: Per my tip above, I'd strongly recommend changing the variable name $Business to match the field name - $RetailerID in this case
echo ($row['RetailerID'] == $Business) ? ' selected' : '';
echo ">" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option>";
}

Related

Comments not adding when submit button is pressed with PHP

Practising PHP by creating a very simple page that has a picture and the user can comment on it. I pretty much have everything down except adding the comment to the table within the database. I have it so I get an alert when the comment either gets added to the table or it does not go through. As far as I can tell, the code looks good but I could be wrong.
Here is the PHP file with the config info
<?php
$servername = "localhost";
$user = "user1";
$password = "";
$dbname = "comment_section";
//Create connection to database
$conn = mysqli_connect($servername, $user, $password, $dbname);
if(!conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE comment_list (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
nid VARCHAR(128) NOT NULL,
comments TEXT NOT NULL,
date datetime NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table comment_list created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
And here is my index file
<?php
include 'comments.php';
error_reporting(0);
if (isset($_POST['submit'])) {
$name = $_POST['nid'];
$comment = $_POST['comments'];
$sql = "INSERT INTO comment_list (nid, comments)
VALUES ('$name', '$comment')";
$result = mysqli_query($conn, $sql);
if ($result) {
echo "<script>alert('Comment added')</script>";
} else {
echo "<script>alert('Comment not added')</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<!-- CSS, JS, and PHP files goes here -->
<link rel="stylesheet" href="style.css">
<!-- javascript code goes here -->
<!-- end of js code -->
</head>
<body>
<!-- Intro to what the site is about, possible pages to include comments -->
<header>
<h1></h1>
<nav>
<ul>
</ul>
</nav>
</header>
<!-- Image with comment section -->
<article>
<img src="images/IMG_1560.JPG" alt="" ">
<div class="wrapper">
<form action="" method="POST" class="form">
<div class="name">
<label for="name">Name</label>
<input type="text" name="nid" id="nid" placeholder="Name" required>
</div> <!-- End div class name -->
<div class="comment">
<label for="comment">Comment</label>
<textarea name="comments" id="comments" placeholder="Comment" required></textarea>
</div> <!-- End of div for textarea -->
<div class="but">
<button name="submit" class="btn">Post Comment</button>
</div>
</form>
<?php
$sql = "SELECT * FROM comment_list";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<?php echo $row['nid']; ?>
<p><?php echo $row['comments']; ?></p>
<?php
}
}
?>
</div>
</article>
<footer>
<p></p>
</footer>
</body>
</html>
Now every time I try to test and click on the submit button. I get an alert and the Comment Not Added pops up. Am I missing something? I also want it to show under the form whenever a user has left a comment. I know I can use Ajax without having to refresh the page, but I at least want to get the comment into the db/table and displayed under the form.

Insert a random image in mysql database using php

I am trying to make a CRUD application. on the Create page I have to have three fields (title, text, category). the problem is that I have to make a method / function in PHP or JS that chooses a random picture from the "images" file and automatically loads it in the database along with the other 3 fields. then it has to appear on the admin.php page together with the other 3 fields.
Images have almost the same name except the last digit which differs (1-2-3)
I have no idea how to make this method/function.
my create.php page
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$title = $text = $category = "";
$title_err = $text_err = $category_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate title
$input_title = trim($_POST["title"]);
if(empty($input_title)){
$title_err = "Please enter a title.";
} else{
$title = $input_title;
}
// Validate text
$input_text = trim($_POST["text"]);
if(empty($input_text)){
$text_err = "Please enter an text.";
} else{
$text = $input_text;
}
// Validate category
$input_category = trim($_POST["category"]);
if(empty($input_category)){
$category_err = "Please enter the category.";
} else{
$category = $input_category;
}
// Check input errors before inserting in database
if(empty($title_err) && empty($text_err) && empty($category_err)){
// Prepare an insert statement
$sql = "INSERT INTO informatii (title, text, category) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_title, $param_text, $param_category, );
// Set parameters
$param_title = $title;
$param_text = $text;
$param_category = $category;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: admin.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
}
?>
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper {
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Create Record</h2>
<p>Please fill this form and submit to add employee record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>title</label>
<input type="text" name="title"
class="form-control <?php echo (!empty($title_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $title; ?>">
<span class="invalid-feedback"><?php echo $title_err;?></span>
</div>
<div class="form-group">
<label>Text</label>
<textarea name="text"
class="form-control <?php echo (!empty($text_err)) ? 'is-invalid' : ''; ?>"><?php echo $text; ?></textarea>
<span class="invalid-feedback"><?php echo $text_err;?></span>
</div>
<div class="form-group">
<label>Category</label>
<textarea name="category"
class="form-control <?php echo (!empty($category_err)) ? 'is-invalid' : ''; ?>"><?php echo $category; ?></textarea>
<span class="invalid-feedback"><?php echo $category_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
this should get you in the right direction (saving the image src is enough), you of course will have to adapt the path to your image folder, and image name
$nr_images = 3;
$random_nr_index = random_int(1,$nr_images);
$random_image_src = '/images/image-'.$random_nr_index.'.jpg';
To do it you need more than one step creating:
A simple html page to post 3 fields value and the image
A php file that receive the post fields and the image and save into mysql
A simple admin.PHP page that shows 3 fields and image
if you already have the images on the server please specify it in a comment
STEP 1:
<html>
<body>
<form method="POST" action="post.php">
f1:<input type="text" name="field1"><br>
f2:<input type="text" name="field2"><br>
f3:<input type="text" name="field3"><br>
im:<input type="file" name="image"><br>
<input type="submit" value="Save">
</form>
</body>
</html>
STEP 2: post.php
<?php
$f1=$_POST["field1"];
$f2=$_POST["field2"];
$f3=$_POST["field3"];
$im=$_POST["image"];
if ($f1 == "" || $f2 == "" || $f3 == "" ){
die("Errors: fields can't be empty! Go back check the fields and try Again");
}
//Saving image on Server's file system if any image
if(isset($_POST["image"])) {
//Saving image with no checking nothing: filetype, mime , extention (it may be very dangerous in a real server exposed to the public)
$where_save = "images/";
$im_name = basename($_FILES["image"]["name"]);
$tmp_name = $_FILES["image"]["tmp_name"];
move_uploaded_file ( $tmp_name , $where_save.$im_name );
}
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// WARNINGS ------------------------------------------------
// I do not care about security , please pay attention to it .
// use some mysql_escape_string , or real_mysql_escape_string
// could mitigate the violence of some sqlinjection attack
$sql = "INSERT INTO yourtable (field1, field2, field3,im_name)
VALUES ('$f1', '$f2', '$f3',$im_name)";
//executing mysql query to save data into it
if (!mysqli_query($conn, $sql)) {
die("Error: " . $sql . "<br>" . mysqli_error($conn));
}
//closing connection
mysqli_close($conn);
//Now we can redirect the user to admin.php where we show data
header("Location: admin.php");
?>
STEP 3:
<?php
$where_are_images="images/";
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Again creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//now we want to read the data from mysql
$sql = "SELECT * FROM yourtable LIMIT 1"; //just limit to the first record
$result = mysqli_query($conn, $sql);
?>
<html>
<body>
<h2>Admin page</h2>
<em> hey every one can see top secret data here , Needs soma care about security!</em>
<?php while($d = mysqli_fetch_assoc($result)){ // LOOPING ?>
<br>
f1:<?= $d["field1"] ?><br>
f2:<?= $d["field2"] ?><br>
f3:<?= $d["field3"] ?><br>
<img src="<?=$where_are_images.$d['im_name']?>">
<br>
<br>
<?php } ?>
</body>
</html>
<php? // CLOSING AND FREE RESOURCES
mysqli_free_result($result);
mysqli_close($conn); ?>
Now you have all you need . Have fun editing it with random images part ...
I hope there are no error (i have not tested it)

Why will my input form not find a matching user to my search inside of my table?

I am trying to create a PHP search that looks through my table (users) and finds the user that matches the name they searched for and displays it on the screen. But the program won't display the user I searched up, and I don't know why. The variables all check out, and I didn't misspell anything in the code or table. My ifelse statement tells me that there is no query result, even though the user in the table and the user I searched are identical. I am using PHPMyAdmin to manage the tables and see changes (if there are any) to the table. The result I wanted was for the program to display the user and email on the page. I can't find a solution, so if you can please tell me!
addnone.php
<?php
include_once 'includes/db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>SCIENCE FAIR</title>
<link rel="stylesheet" href="style.css">
<section class="container grey-text">
<form class="white" action="addnone.php" method="POST">
<tr>
<label>First Name:</label>
<td><input type="text" name="firstname" placeholder="First Name"></td></br>
</tr>
<div class="center">
<td colspan="2"><input type="submit" name="submit" value="Search"></td>
</div>
</form>
<div class="box">
<?php
if (isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$sql = "SELECT * FROM users WHERE name = '%$firstname%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<div>
<p>".$row['name']."<p>
<p>".$row['email']."<p>
</div>";
}
} else {
echo "No users with name $firstname!";
}
}
?>
</div>
</section>
</html>
db_connect.php
<?php
$dbServername = "localhost";
$dbUsername = "scifair";
$dbPassword = "password";
$dbName = "scifair";
// connect to database
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
?>
Use "LIKE" Operator
$sql = "SELECT * FROM users WHERE name LIKE '%$firstname%'";

When adding a value from an input field to the database to an existing number, the number added is double

When the inputted number for $points is taken in the inputted field, it adds the number to the total already in the database, but for some reason the number added is double. For example if input 3, 6 will be added to the total. Can anyone help with an answer to this?
The idea is that someone should be able to add points to the total, and then on a separate page able to view it in a progress bar (which is working correctly) but the totals do not add up.
I am new to php so sorry in advance for any mistakes throughout the code.
Thank you
<?php
session_start();
if(!isset($_SESSION["sess_user"])){
header("location:login.php");
} else {
echo "Userid: ".$_SESSION["sess_id"];
?>
<!doctype html>
<html>
<head>
<h2><a id="button" href = "index.php">Main Menu</a></h2>
<h2><a id="button" href = "selftrack.php">Track your updated progress!</a></h2>
</head>
<body>
<?php
// Connect to the database
$username = "";
$password = "";
$host = "";
$db = $username;
$points = $_POST['self_p'];
// Connect to the MySQL server and select the required database
$connection = mysqli_connect($host, $username, $password, $db);
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else { // Database connected correctly
echo "<h1>Add daily points</h1>";
if (isset($_POST["addSubmit"])) {
if ((!empty($_POST["self_p"]))) {// Check all parts of the form have a value
$query="UPDATE targets
SET self_points = self_points + ".$points."
WHERE user_id='".$_SESSION['sess_id']."'";
$result = mysqli_query($connection, $query);
if ($result == false) {
// Show error message
echo "<p>The target points for " . $_POST["self_p"] . " was not added.</p>";
}
else {
echo "<p>The target points for \"" . $_POST["self_p"] . "\" has been added.</p>";
}
}
else {
echo "<p>Please fill out all the details</p>";
}
}
}
?>
<form role="form" id="addForm" name="addForm" action="?" method="post">
<div class="form-group">
<div class="col-xs-7">
<label for="addFormLast_Name">Please enter your daily points, up to 5:</label>
<input class="form-control" id="addFormLast_Name" name="self_p" type="text">
</div>
<div class="form-group">
<div class="col-xs-7">
<input class="form-control" id="addSubmit" name="addSubmit" value="Add Target" type="submit">
</div>
</div>
<?php
mysqli_close($connection);
}
?>
</body>
<?php
?>
</html>

PHP update user account details no error displayed but account details not updated

Overview:
I am crating a dummy website for learning purposes therefore its functionalists are basic and security in not on the agenda atm.
Actual Problem:
OK so my application loges in a users who has an option of editing his/hers account if desired. So i have gone ahead and created PHP script that soopose to deal with this BUT IT DOES NOT. When I click edit account button no errors pop up but at the same time when i check MySQL database no changes occurred.
EditAccountForm.php file:
<?php
include('connect_mysql.php');
if(isset($_POST['editAccount'])){
$Newusername = $_GET['username'];
$Newpassword = $_POST['password'];
$Newfirstname = $_POST['first_name'];
$Newlastname = $_POST['last_name'];
$Newemail = $_POST['email'];
if($Newusername != $username)
{
$q1 = ("UPDATE users SET username=$Newusername WHERE username=$username");
}
else if(!mysql_query($q1)){
echo "MySQL ERROR: " . mysql_error() . "" . $sql;
}
///////////////////////////////////////////////////////////////
if($Newpassword != $password)
{
$q2 = ("UPDATE users SET password=$Newpassword WHERE password=$password");
}
else if(!mysql_query($q2)){
echo "MySQL ERROR: " . mysql_error() . "" . $sq2;
}
///////////////////////////////////////////////////////////
if($Newfirstname != $firstname)
{
$q3 = ("UPDATE users SET first_name=$Newfirstname WHERE first_name=$firstname");
}
else if(!mysql_query($q3)){
echo "MySQL ERROR: " . mysql_error() . "" . $sq3;
}
///////////////////////////////////////////////////////////////
if($Newlastname != $lastname)
{
$q4 = ("UPDATE users SET last_name=$Newlastname WHERE last_name=$lastname");
}
else if(!mysql_query($q4)){
echo "MySQL ERROR: " . mysql_error() . "" . $sq4;
}
///////////////////////////////////////////////////////////////
if($Newemail != $email)
{
$q5 = ("UPDATE users SET username=$Newemail WHERE email=$email");
}
else if(!mysql_query($q5)){
echo "MySQL ERROR: " . mysql_error() . "" . $sq5;
}
}
?>
userEditAccount.php:
<html>
<head>
<title>Edit Account</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<header><h1>E-Shop</h1></header>
<article>
<h1>Welcome</h1>
<h1>Edit Account</h1>
<div id="login">
<ul id="login">
<form method="post" name="editAccount" action="userEditAccount.php" >
<fieldset>
<legend>Fill in the form</legend>
<label>Select Username : <input type="text" name="username" /></label>
<label>Password : <input type="password" name="password" /></label>
<label>Enter First Name : <input type="text" name="first_name" /></label>
<label>Enter Last Name : <input type="text" name="last_name" /></label>
<label>Enter E-mail Address: <input type="text" name="email" /></label>
</fieldset>
<br />
<input name="Editsubmited" type="submit" submit="submit" value="Edit Account" class="button">
</form>
<?
echo $newrecord;
?>
</div>
<form action="userhome.php" method="post">
<div id="login">
<ul id="login">
<li>
<input type="submit" value="back" onclick="index.php" class="button">
</li>
</ul>
</div>
</article>
<aside>
</aside>
<div id="footer">This is my site i Made coppyrights 2013 Tomazi</div>
</div>
</body>
</html>
Furthermore:
I tried to fiddle with the code looked on web but no luck the code i have written for this script in my eyes is the best solution and the one that makes sens to me.
So i had no other option but turn to this website to look for answers, can anyone perhaps see where am going wrong with this whole thing...?
Image of the Edit Account page:
As Asked Conect_mysql.php:
<?php
$db_hoast = "127.0.0.1";
$db_username = "root";
$db_password = "";
$db_name = "eshop";
$con = mysql_connect("$db_hoast","$db_username","$db_password");
if(!$con)
{
die("Could not connect to DATABASE");
}
$db = mysql_select_db("$db_name");
if(!$db)
{
die("No database");
}
?>
the problem with your UPDATE statements are the values are not wrapped with single quotes. They are string literal and should be wrapped.
$q1 = "UPDATE users SET username='$Newusername' WHERE username='$username'";
in order to display the error,
if($Newfirstname != $firstname)
{
$q1 = "UPDATE users SET username='$Newusername' WHERE username='$username'";
$result = mysql_query($q1);
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
}
Also your logical UPDATES are wrong. This causes you to updates records that matches with the conditions.
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?

Categories