Trouble updating phpmyadmin DB - php

Database values not updating
Working on a web form here. I want to update user info in a database. Using AJAX to pull from a list and generate information. When “Update Information” is clicked, the database should update the given values. I am just testing it on “FirstName” for now. The Code runs and I get no errors, but my database is not updating.
Process.php:
<body>
<?php
if (!isset($_SESSION['email']))
Header ("Location:logout.php") ;
if(isset($_POST['submit'])){
$NewFirstName = trim($_POST['NewFirstName']);
$StudentPID = $_POST['ca'];
$sql = "update Student SET FirstName=".$NewFirstName."where StudentPID = ".$StudentPID."";
$PleaseUpdate = mysql_query($sql);
//echo "<script type='text/javascript'>alert('Data was successfully inserted')</script>";
}
?>
<form name="input" action="process.php" method="post">
Ajax Demo
<br/><br/>
Select a Student: <br/><br/>
<select name="ca" onchange="showDetail(this.value)">
<?php print GetCategory(); ?>
</select>
<div id="txtHint"><b>Person info will be listed here.</b></div>
<?php ?>
<br />
<input type="submit" name = "submit" value="Update Information">
</form>
<br/><br/>
Logout
</body>
</html>
GetDetail.php:
<?php session_start(); //this must be the very first line on the php page, to register this page to use session variables
//if this is a page that requires login always perform this session verification
require_once "inc/sessionVerify.php";
require_once "dbconnect.php";
if (!isset($_SESSION['email']))
Header ("Location:logout.php") ;
$q = $_GET['q']; //get the values passed from this query string
$sql = "select * from Student where StudentPID = '".$q."'";
$result = $DB->GetAll($sql);
//display the result in a table
print '<br /><br /><span style="color:red">Data retrieved from database:</span><br/ >';
//get the rows
$i = 0; //This is used to remember how many checkboxed created in total
foreach ($result as $row)
{
//Now make the form
print( '<form action="getDetail.php" method="post">
First Name: <input type="text" id="NewFirstName" name="NewFirstName" value='.$row["FirstName"].'><br>
Last Name: <input type="text" id="" name="" value='.$row["LastName"].'><br>
</form>
');
}
print '</table>';
?>

Related

Trying to write to a mysql database but it keeps coming up empty set

For a school project I am trying to write to a table called enrolment where the student number and the course they have selected are added after they have been tested to make sure the student name and number exists in another database. No errors are coming up, however when I check my database afterward enrolment says its an empty set. Does anyone have suggestions?
<?php
require 'connect.php';
//making a variable from the user data
$name = $_POST["name"];
$number = $_POST["snumber"];
$course = $_POST["pcourse"];
//linking up the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());
// select all from table student which show student name and number
$squery = "SELECT * FROM student";
$sresult = mysqli_query($link, $squery);
$found = 0;
while ($srow = mysqli_fetch_array($sresult)) {
// testing if the student name and number match the users data
if ($name == $srow['family'] && $number == $srow['uid']) {
$enrol = "INSERT INTO enrolment (uid course) VALUES('$number' '$course')";
$found = 1;
break;
}
}
mysqli_close($link);
?>
<html>
<body>
<form action="index.php" method="post">
<br>
<input type = "submit" value="back" name="back">
</form>
</body>
</html>
index.php (form)
<!DOCTYPE html>
<html>
<body>
<h1>Course Selection</h1><br>
<form action="next.php" method="post">
Name: <input type="text" name="name" placeholder="Name" required="required" maxlength="50">
<br><br>
Student Number: <input type="text" name= "snumber" required="required" maxlength="9">
<br><br>
<?php
//form
require 'connect.php';
echo "Select a course: <select name = \"pcourse\">\n";
$link = mysqli_connect(HOST, USER, PASS, DB) or die(mysqli_connect_error());
$query = "SELECT * FROM course";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo "<option> $row[code] $row[name] $row[maxenroll]</option><br>";
}
mysqli_free_result($results);
mysqli_close ($link);
echo " </select>\n";
?>
<br><br>
<input type = "submit" value="submit" name= "submit">
</form>
</body>
</html>
Your insert code just a string. You should send to mysql your insert code. Try this
$enrol = "INSERT INTO enrolment (uid, course) VALUES($number, $course)";
$link->query($enrol);
My guess is that when checking the result set from student table - there is no such family and uid in it, which means - in the table. Instead of doing insert right away, try to display matching record from the database - if this is actually what you wanted to find. Then you can check what is actually stored in the database - and you can compare both.
Other thing is - why not limit select to exact that student?
Rebuild your query, something like:
$squery = "select * from student where family='".$name."' and uid='".$number."'".
Then you can check how many records were selected and display that number before doing any inserts.

Increment id on click in MySQL

I have a problem to visualize the solution for the problem that I have now.
The user is allowed to insert a row in a table.
And I try to display a button (input) +1 who allow the user to increment a column (vote) in a selected row among all created.
The problem is that I don't get the thing for rely incrementation to the desired id.
Here my code :
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['mainsubmit']))
{
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease(name) VALUES(:name)');
$req->execute(array('name' => $nameDisease));
}
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch())
{
$id = $result['id'];
echo $id ?>
<form action="" method="post"> <input name="secondsubmit" type="submit" value="+1"> </form><?php
if(isset($_POST['secondsubmit']))
{
$db->exec("UPDATE disease SET vote = vote + 1 WHERE id = " .$id);
}
}
Logically, the code above doesn't work but I don't understand how find the solution.
In brief, i want to allow the user to increment a column in a selected row.
Thanks
Edit: Shadow, it's not my problem because your solution is used for automatically chose between INSERT or UPDATE if the line doesn't exist or exist. Me, I want allow the user to create rows and allow he to vote +1 on each of one that exist, and it will not be possible for he to insert a row from the input +1.
I created code snippet similar to your code style.
You have two submit buttons so you need to separate handling of those two requests.
The $id of the item you want to update in the second submit need's to come from hidden value in form.
In order for this to work you need to create table in mysql:
create table disease (id MEDIUMINT NOT NULL AUTO_INCREMENT, name VARCHAR(20), vote INTEGER, PRIMARY KEY (id)); - for example like this
<html>
<body>
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
$db = new PDO('mysql:dbname=phpapp;host=db', 'root', 'phpapptest');
if (isset($_POST['mainsubmit'])) {
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease (name, vote) VALUES(:name, 0)');
$req->bindParam(':name', $nameDisease);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) { ?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
if (isset($_POST['secondsubmit'])) {
$req = $db->prepare("UPDATE disease SET vote = vote + 1 WHERE id = " . $_POST['id']);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) {?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
?>

If content exists in database, provide form to update it - else provide form to add new row

It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting

Show phpmyadmin cell in html textbox value

I have a database in phpmyadmin called fleet hire motors, and in that database is a table called customer.
In that table are columns called customerID and Surname. I have already done some coding on one page that lets the user select the customerID to edit the Surname.
On the next page I want a textbox. in that textbox, the default value should be what the current Surname is.
So, if i was to edit customer with customerID 1 (of which surname is currently Brown and I want to change to Green) the second page would show Surname: [Brown], where [] encloses a textbox.
I currently do not have any code, and would like to keep it primarily php. The first page is called editcustomer.php, and the second is called editcustomer2.php.
Any help is appreciated.
My current code is:
<html> <head> <title>Edit Customer</title> </head><body>
<?php mysql_connect("localhost","username","password") or die(mysql_error());
mysql_select_db("fleet hire motors") or die(mysql_error()); ?>
<?php
$CustomerID = $_GET["CustomerID"];
$query=mysql_query(" SELECT * FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
b$CustomerID = $row["CustomerID"];
} ?>
First Name: <input name="FirstName" type="text" value="
<?php
$FirstName = $_GET["CustomerID"];
include 'db.php';
$query=mysql_query(" SELECT FirstName FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
?> ">
<br> <input name="submitbtn" type="submit" value="Save"> <input name="resubmitbtn" type="submit" value="Reset"> </form> </body> </html>
Sorry for all the edits, as I am new to stackoverflow and just learning how to do it.
I have now updated my coding thanks to a response, but it is still not working. My most current coding is:
<html>
<head>
<title>Edit Customer</title>
</head>
<body>
<?php
mysql_connect("localhost","username","password") or die(mysql_error());
mysql_select_db("fleet hire motors") or die(mysql_error());
?>
<?php
$CustomerID = $_GET["CustomerID"];
$query=mysql_query(" SELECT * FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
$row = mysql_fetch_array($query);
if (!$row || !is_array($row)){
$CustomerID = 0;
$CustomerFirstName = '';
}
else {
$CustomerID = $row["CustomerID"];
$CustomerFirstName = $row['FirstName'];
}
?>
First Name: <input name="FirstName" type="text" value="<?php echo $CustomerFirstName; ? >">
<input name="submitbtn" type="submit" value="Save">
<input name="resubmitbtn" type="submit" value="Reset">
</form>
</body>
</html>
This does not give me anything in the textbox, and my submit button does not work.
You'll have to make an echo.
In case that your customerId shall be unique you did not need a while.
[...]
<?php
$CustomerID = $_GET["CustomerID"];
$query=mysql_query(" SELECT * FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
$row = mysql_fetch_array($query));
if (!$row || !is_array($row)){
$CustomerID = 0;
$CustomerFirstName = 'NoNameFound';
}
else {
$CustomerID = $row["CustomerID"];
$CustomerFirstName = $row['FirstName'];
}
//Debug
echo 'rowcontent: <pre>' . print_r($row, true) . '</pre>';
?>
First Name: <input name="FirstName" type="text" value="<?php
echo $CustomerFirstName;
?>">
[...]
You should also do some validation on your GET and POST before using them in your database e.g.
is_numeric($CustomerId)
or something like
[...] WHERE MD5(CustomerId) = ' . md5($CustomerId) . ' [...]

php form not posting to self

I have a simple dropdown menu which posts the result to itself but when i choose one of the options in the drop down menu it does not echo back the result as expected.
I'm sure i've just missed out something simple but can't spot it. Any ideas? The form posts but does not echo back $user_settings.
<?php
include "functions.php";
connect();
$sql="SELECT user_id, user_realname FROM users ORDER BY user_realname ASC";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$name=$row['user_realname'];
$options.="<OPTION VALUE=>".$name.'</option>';
}
if(isset($_POST['submit'])){
$user_realname = $_POST['username_select'];
$user_select = mysql_query("SELECT user_id, user_realname FROM users WHERE user_realname = '$user_realname'")
or die ("Could not get user data");
while($row = mysql_fetch_array($user_select)){
$user_settings = $row['user_id'];
echo $user_settings;
}
}
?>
<html>
<head>
<body>
<form action="<?php echo $PHP_SELF;?>" method="POST">
<tr><label>Choose User to Edit</tr>
<tr><SELECT NAME="username_select"><OPTION VALUE=""></option>User's Name<?php echo $options;?></SELECT></label></tr>
<tr><input type="submit" value="submit" name="submit"></tr>
</form>
<?php echo $user_settings;?>
<br/>
Go Back
</body>
</head>
</html>
User $_SERVER['PHP_SELF'] instead of $PHP_SELF

Categories