Insert into specific column mysql database php - php

I want to enter data into my mysql db but into a specific row, when the user enters a number and clicks a button. For example, if the user logged in, is called 'user', then the data which is entered will go into a column called 'ticket' which is in the same row as the username 'user'.
I have written the code for it to go into the db but in a new row:
Code for page which user enters the data:
<?php require('check.php')?>
<html>
<head>
<title><?php echo $row['username']; ?> Profile</title>
</head>
<body>
<p style="float: right">LOG OUT</p>
<?php
include ('connect.php');
$user_id= $_SESSION['id'];
$sql = "SELECT username FROM user WHERE user_id = '$user_id'";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
$uname = mysql_fetch_array($result);
$user_id= $_SESSION['id'];
$sql = "SELECT email FROM user WHERE user_id = '$user_id'";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
$uemail = mysql_fetch_array($result);
echo "Hello" . " " . $uname['username'];
?>
<h1>Choose ticket Amount</h1>
<hr />
<form method="post" action="addticket.php">
<label for="elliegoulding">Ellie Goulding Ticket Amount: </label>
<input type="text" name="elliegoulding" max="3" maxlength="3" /><br />
<br />
<input type="submit" value="Add ticket"/>
<br />
<hr />
<div id="footer">
</div>
</form>
</body>
</html>
Code for php page which processes information and adds to db:
<?php
$elliegoulding = $_REQUEST["elliegoulding"];
$linkme = mysql_connect("mysql.cms.gre.ac.uk","ta210","*****");
if (!$linkme)
die ("Could not connect to database");
mysql_select_db("mdb_ta210", $linkme);
$query = "INSERT INTO user (ticket) VALUES ('$elliegoulding, Ellie Goulding Tickets')";
mysql_query ($query, $linkme)
or die ("Ticket purchase failed.");
echo ("You have just bought $elliegoulding Ellie Goulding tickets");
mysql_close($linkme);
?>
Like I said the above code works and enters it into the database but just into a new row.
Any help or suggestions would be great.

INSERT will only add a new row and you don't want that. You need to UPDATE the row.
Something along the line of... :
$query = 'UPDATE user SET ticket="Ellie Goulding rocks!" WHERE username="'.$user.'"';
Make sure that username is unique (can't have 2 "Pierre" in your database or both users will get updated).

Related

Search value from Input box in mysql php [duplicate]

This question already has answers here:
search data from html input in mysql
(2 answers)
Closed 1 year ago.
I am trying to search the username from table by using form method in HTML with submit button, and what i really want is that when user write his email address in input box and press submit, the query should echo username associated with that email address.
But the problem is that when I press search button, it is showing all the usernames on that table instead of only one. My table "payments" containing the following values: id, product id, payer_email, username, password.
My code is as under. Thanks in advance.
<?php
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM payments WHERE payer_email LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Username: ' .$row['username'];
}
}
?>
</body>
</html>
try this
<?php
if (!empty($_REQUEST['payer_email'])) {
$term = mysql_real_escape_string($_REQUEST['payer_email']);
$sql = "SELECT * FROM payments WHERE payer_email ='{$term}'";
$r_query = mysql_query($sql);
$row = mysql_fetch_assoc($r_query)
echo 'Username: ' .$row['username'];
}
?>

Pre Complete HTML Form with PHP and MYSQL

I am creating a simple page which updates a single record tempKey=1, single field reqdTemp MySQL dBase. I have the form working fine; it updates the record, then returns to the initial form ready for the user to change the temperature again.
Q: I would like the form to be pre-populated with the existing information from the database so the user sees the current required temperature about to be changed. I'm not sure where to start!!
The form, updateTemperature.php, is this:
<html>
<body>
<h1>RPi BBQ - Set Temperature</h1>
<form action="insert.php" method="post">
<p>Set Temperature: <input type="text" name="setTemp" /></p><br><br>
<input type="submit" value="Set Temperature" />
</form>
</body>
</html>
The post script, insert.php is this:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: PiBQ_Temp2.php');
mysql_close($con)
?>
To pre-populate the form, query the database for the current value and set that in the returned HTML. So your updateTemperature.php could become something like this:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$currentTemp = 100; // some default
$sql = "SELECT reqdTemp FROM PiBQ_Temp WHERE tempKey = 1";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$currentTemp = $row['reqdTemp'];
}
mysql_close($con);
?>
<html>
<body>
<h1>RPi BBQ - Set Temperature</h1>
<form action="insert.php" method="post">
<p>Set Temperature: <input type="text" name="setTemp" value="<?= $currentTemp ?>" /></p><br><br>
<input type="submit" value="Set Temperature" />
</form>
</body>
</html>

Use PHP to match username & password with HTML drop down

I have a MySQL database called school that is set up like this:
schoolID(1), schoolName(school 1), schoolCounty(Buckinghamshire), schoolUsername(school1admin), schoolPassword(school1password)
I currently have a drop down menu that shows the list of schools and when I type any username and password into the HTML login form I can log in.
I can't seem to work out how I can set it so, depending on the school selection will depend on what username and password to use.
For example, if i select school1 then i can ONLY use school1's username and password.
This is what I have so far for index.php:
<?php
require_once 'databaseConnect.php'; // connects to the databse via this file
if ($conn->connect_error) die ($conn->connect_error); // check the connection to the database. If failed, display error
$sql = "SELECT * FROM school";
$result = $conn->query($sql);
$conn->close();
?>
<html>
<body>
<title>EduKode</title>
<div id="login-form-container">
<p>Log In:</p>
<?php
echo'<div id="schoolSelection">';
echo '<select name="schoolName">';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option>'. $row["schoolName"]. "<br>";
}
} else {
echo "0 results";
}
echo '</select>';
echo'</div>';
//http://stackoverflow.com/questions/10009464/fetching-data-from-mysql-database-to-html-dropdown-list
?>
<form id="login-form" name="contactform" method="post" action="checkSchoolCredentials.php"> <!-- when submitting the form will call the 'authenticate.php' script.-->
<div class="contact-form">
<label>Username:</label>
<input name="username" type="text"> <!-- students created username field-->
<label>Password:</label>
<input name="password" type="password"> <!-- students created password field-->
</div>
<div id="submit-button">
<input type="submit" name="submit" value="Log In">
</div>
</form>
</div>
</body>
</html>
This is for checkSchoolCredentials.php:
<?php
require_once 'databaseConnect.php'; // connects to the databse via this file
if ($conn->connect_error) die ($conn->connect_error); // check the connection to the database. If failed, display error
if(isset($_POST['submit'])) // if submit button is pressed
{
$username = $_POST['username']; //assigns the value of the input box username to $username
$password = $_POST['password']; //assigns the value of the input box password to $password
$query = "SELECT * FROM school WHERE schoolUsername='$username' AND schoolPassword ='$password'"; // Query the database
$result=mysqli_query($conn, $query);
if(mysqli_num_rows($result) ==1)
{
session_start(); // start session
$_SESSION['auth']='true';
$_SESSION['username'] = $username; // save session as username
header('location:taskSelection.php'); // if correct, redirect to taskSelection.php
}
else
{
header('location:index.php'); // redirect to index.html if incorrect
}
}
$conn->close();
?>
You were close, what you have to is to send also the schoolname and check if all variable are set:
if (isset($POST['username'],$POST['userpassword'],$POST['schoolName'])
And then just replace :
$query = "SELECT * FROM school WHERE schoolUsername='$username' AND schoolPassword ='$password'"; // Query the database
with :
$query = "SELECT * FROM school WHERE schoolUsername='$username' AND schoolPassword ='$password' AND schoolName='$schoolName'"; //
Now you have to now know that my query is still bad because it's vulnerable to sql injection. You have to use prepare statements instead:
$sql = "SELECT * FROM school WHERE schoolUsername=? AND schoolPassword = ? AND schoolName=?";
if ($query = $conn->prepare($sql)){
$query->bind_param("s", $username,$password,$schoolName);
$stmt->bind_result($result);
while($stmt->fetch()){
// you can work with $result which is an array containing a line of the results
}
Add AND schoolName = "$schoolName" to your SQL statement

Update MySQL query with PHP

I am trying to overwrite the current data in MySQL to be able to update everything.
I am new to this I don't see any errors with the below code:
PHP code:
<?php
// see if the form has been completed
if (isset($_POST['submit'])){
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
if($firstname && $surname){
// connect to the server
include_once("php_includes/db_conx.php");
// check if that user exist
$exists = mysql_query ("SELECT * FROM users WHERE firstname='$firstname'") or die ("the query could not be connected");
if (mysql_num_rows ($exists) != 0) {
// update the description in the database
mysql_query("UPDATE firstname SET surname='$surname' WHERE firstname='$firstname'") or die ("update could not be applied");
echo "successful";
} else echo "the name does not edist";
} else echo "you need to enter both of the fields try again:";
}
?>
The error I get is
The query could not be connected
but I tried the query and it is fine.
HTML:
<html>
<head>
<title>update MySql form</title>
</head>
<body>
<div id="pageMiddle">
<form action="user1.php" method="POST">
<div>
<p>First Name: <input type="text" name="firstname" id="firstname" ></p>
<p>Surname: <input type="text" name="surname" id="surname"></p>
<p><input type="submit" name="submit" id="submit" value="Update Description"></p>
</div>
</form>
</body>
</html>
Your table is called 'users' but you are running UPDATE on firstname. Change it to:
UPDATE users SET surname...
Then do
$exists = mysql_query ("SELECT * FROM users WHERE firstname='" . $firstname . "'")
in order to isolate whether you have value for that variable. I would recommend printing the query string for testing purposes.

User login (using sessions) trouble

I'm trying to make a log in system for users to login on my site. For some reason I can't seem to get my code to identify that a user exists, it always thinks the user doesn't exist in my database even when it does. I was hoping someone could look over my code and tell me if something is wrong, as I can't find any errors.
Also I should mention I'm very well aware none of this code is safe or secure, I would like to leave it that way for now.
Here is my table information:
<!-- Login form -->
<div id="userLogin">
<form name="user_login" id="Login" method="post" action="loginSF.php">
Username : <input type="text" name="yourUsername" id="username" ><br />
<span id="usernameWarnings" style="color:black"> </span> <br />
Password : <input type="password" name="yourPassword" id="userPassword" > <br />
<span id="passwordWarnings" style="color:black"> </span> <br />
<input type="submit" value="login" onclick="return validateLoginForm()" >
</form>
</div>
Here is my PHP code for loginSF.php: (updated with SQL fix) (Problem still EXISTS)
<?php
session_start(); // starts session
require_once 'databaseLogin.php'; //login info
$db_server = mysqli_connect($db_hostname, $db_username, $db_password, $db_database); //connection
if(mysqli_connect_errno($db_server))
{
echo "failed to connect to mySQL: " . mysqli_connect_error();
}
//$loggedIn = mysqli_query($db_server,"SELECT User_Name FROM members");
$username = $_POST['yourUsername'];
$password = $_POST['yourPassword'];
$query = "SELECT `User_Name`, `Password` FROM `members` WHERE User_Name='$username' AND Password='$password'";
$loggedIn = mysqli_query($db_server, $query);
// check username and password match
if(mysqli_num_rows($loggedIn) == 1)
{
echo "Login Successful";
}
else
{
echo "Login failed";
}
?>
users in database:
User_Name Password
Tester345 tttttt
Your code is vulnerable. I assume it's just a learning project
change
$query = "SELECT 'User_Name', 'Password' FROM `members` WHERE User_Name='$username' AND Password='$password'";
to
$query = "SELECT `User_Name`, `Password` FROM `members` WHERE User_Name='$username' AND Password='$password'";

Categories