I am a beginner to PHP and I am working on a profile page. The current problem is to change the name (This is a trial page that's why i am changing the name).For some reason i am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'lastName ='Lname' WHERE email ='qwerty#example.com'' at line 1.
<?php
include('server.php');
$db = mysqli_connect('localhost','root','','userdata');
$query = "SELECT * FROM data WHERE email = '".$_SESSION['username']."'";
$result = mysqli_query($db,$query);
$data = mysqli_fetch_assoc($result);
?>
<html>
<head>
<title>Profile</title>
</head>
<body>
<form method="POST" action="">
<p>First name: <input type="text" name="fname" value="<?php echo htmlspecialchars($data['firstName']); ?>" > </p>
<p>Last name: <input type="text" name="lname" value="<?php echo htmlspecialchars($data['lastName']); ?>"> </p>
<p><input type="Submit" name="confirm" value="Confirm"></p>
</form>
<?php
if(isset($_POST['confirm']))
{
$db = mysqli_connect('localhost','root','','userdata');
$query = "UPDATE data SET firstName ='".$_POST['fname']."' lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
mysqli_query($db,$query);
echo mysqli_error($db); //For checking error.Remove afterwords.
}
?>
<p>HOMEPAGE</p>
</body>
</html>
The server.php is a page where I manage the backend of the entire operation so it's not involved in this operation.The first PHP block takes data from the table. The HTML block creates a form where the user can edit the data. The PHP block should update data into the table.
I would appreciate any tips to further improve my page as i am still new to this.Thanks in advance
UPDATE:- Adding , to the query still does not change the situation.
you have an error in your sql statement (as the error message suggests). in mysql the error message usually points out the exact position where the error occurs, and it usually quotes the first character/word that causes the problem.
in your case, that's lastname. Your update query so far is:
UPDATE data SET firstName ='fname' lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ error occured here
when you look-up how UPDATE queries are supposed to look like (mysql docs) you'd find, that the different updated fields must be separated by comma:
UPDATE data SET firstName ='fname', lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ add this here
also, you're vulnerable to sql injections (please read up on them, and how to prevent them - this is done by prepared statements)
Please try with that(there was a missing comma on your SQL query).
$query = "UPDATE data SET firstName ='".$_POST['fname']."', lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
The other problem of using code that is open to sql injection is you can easily change the syntax of an sql statement from the input side. For example if for last name you input "O'connor", you change the syntax. Try to use echo $query and then analyse the output or better still,copy it and run it directly without using php
As mentioned in the comment. When updating multiple fields you need to comma separate them:
UPDATE data
set
field1="meh", /* <-- comma */
field2="foo"
where otherField="something"
Related
I have the following form:
<form id ="classadderform" action="formsubmit.php" method="POST">
<input type ="checkbox" name="note" value = "Note1"></input>
<input type="submit" value="Click Me" style="width:300px;">
</form>
Upon submit, the code redirects to formsubmit.php. Part of the code there is the following:
$db = new mysqli("sql...byethost8.com", "b8_163//....(database info));
$id = $_SESSION['id'];
.......
if(isset($_POST['note'])){
if($id){
$db->query("UPDATE answers SET WordLevel = 'Difficult' WHERE user_id=$id"); //<<<UPDATES SUCCESSFULLY
$notevalue=$_POST['note'];
$db->query("INSERT INTO answers (user_id, ValueColumn) VALUES ($id,'$notevalue')"); //<<<<<DOESN'T UPDATE
The WordLevel column updates successfully, but the value of the input named note does not insert into the column titled ValueColumn. This was working in my code a few days ago but it somehow stopped working. I tried different iterations of single quotes around $id and $notevalue but nothing seems to resolve the issue.
Any help would be much appreciated!
Execute and clear before the second query.
O you can try concating queries together using semicolon
$db->query("FIRST QUERY ; SECOND QUERY");
If you dont need the output of first query.
PDO multiple query
mysqli multiple query
might also help real_query
I have a form in HTML which posts two values hostname and ip_address.
<form action="demo-select.php" method="post" />
<p>HOSTNAME/IPADDRESS: <input type="text" name="HOSTNAME" name="IP_ADDRESS" /></p>
<input type="submit" value="Submit" />
</form>
If I enter the hostname/ip_address and submit it, it will take me to demo-select.php script.
In demo-select.php script I'm able to get the output for hostname from my MySQL db. How should I get the output based on ip_address?
$value = $_POST['HOSTNAME'];
$query = "SELECT * FROM <tablename> WHERE HOSTNAME='$value'";
$result = mysql_query($query);
This script connects to a MySQL db and gets the output based on the hostname. What modifications should I make to get the output based on ip_address as well?
Table columns:
HOSTNAME
IP_ADDRESS
cpus
MEMORY
HTML:
You can't assign two names to an HTML element. I'd suggest that you either use two fields or use a dropdown / radio button along with the form field for the user to specify whether they're entering a hostname or an ip_address:
<form action="demo-select.php" method="post" />
<select name="address_type">
<option value="ip"> IP Address </option>
<option value="host"> Host Name </option>
</select>
<input type="text" name="host_name_or_address" />
<input type="submit" value="Submit" />
</form>
An assumption here is that you'd want the user to enter as input only one of hostname or ip_address in a single submit. If you want both to be relayed to the PHP at once, then please get rid of the select dropdown and use two input fields instead.
PHP:
Check what's been received in address_type and determine what query to use accordingly:
$address_type = $_POST['address_type'];
$value = $_POST['host_name_or_address'];
if($address_type == "host"){
// If looking for partial matches, use... WHERE HOSTNAME LIKE '%$value'
$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value' ";
}
else{
$sql = "SELECT * FROM <tablename> WHERE IP_ADDRESS = '$value' ";
}
Again, if you want both fields to be searched for at once, then along with the HTML edits indicated in the narration above, you'll have to receive in a PHP variable the value of the second input field too. Also then please get rid of the if-else construct here above and write a single, combined query as:
$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value1' AND IP_ADDRESS = '$value2' ";
Finally, please don't use mysql_*() functions in any PHP code. They're long deprecated and are very vulnerable to SQL Injection Attacks as Daniel has already suggested in his answer. Please have a look at MySQLi and PDO Prepared Statements instead. These utilities provide a cleaner way to write your queries and also a much safer mechanism to shield them against potential risks.
Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...
I want to update a text field in my mysql database but it doesn't change when I run the query. I've tried stripping special characters but it still doesn't work.
UPDATE: It returns the following error: It gives the following error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'datatext='LET OP! Aantal Mate' at line 1
Here is the data:
The HTML
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="hidden" name="nr" value="1">
<textarea rows="20" cols="50" name="text"></textarea>
</form>
The PHP
$change_text = $_POST['text'];
$change_nr = $_POST['nr'];
if ((!empty($change_text))&&(!empty($change_nr)))
{
mysql_query("UPDATE table SET datatext='$change_text' WHERE datanr='$change_nr'");
}
Structure MySQL (tablename = table)
datanr = int(6)
order = text utf8_general_ci
The text area is not to blame. your sql references a column name that your table doesn't seem to have.
Your schema has datanr and order while the update query has datanr and datatext.
Some more tips:
don't use mysql keywords as column or table names or at least escape them with `backticks` if you must.
always validate/sanitise your user input
don't use mysql but use mysqli, pdo or better yet, a good data access layer
try to check with key exists instead empty
if (array_key_exists('nr', $_POST)) {
$change_text = $_POST['text'];
$change_nr = $_POST['nr'];
mysql_query("UPDATE table SET datatext='$change_text' WHERE datanr='$change_nr'");
}
Debug your code
var_dump($_POST);
$change_text = $_POST['text'];
$change_nr = $_POST['nr'];
if ((!empty($change_text))&&(!empty($change_nr)))
{
$sqlString = "UPDATE table SET datatext='$change_text' WHERE datanr='$change_nr'";
var_dump($sqlString);
mysql_query($sqlString) or die(mysql_errno() . " " . mysql_error());
}
Your form lacks <input type="submit" />. Without submit button, form (and data) cannot be submitted.
Haha! I know the problem! It is the query. You must use those special quotes around column names. Like this: mysql_query("UPDATE table SET datatext='$change_text' WHERE datanr='$change_nr'");
Notice ` quotes aound datatext. Now your script should work. If it doesn't, I will shut down my pc and go to bed immediatelly lol
Your query should be like this:
mysql_query("UPDATE table SET datatext='".$change_text."' WHERE datanr=".$change_nr);
I have been working on something like a sign up form for a facebook app but instead of INSERT it UPDATE because before that I have already INSERT
$inserP = "INSERT INTO particular (id, name)
VALUES ($userid, 0)";
pg_query($conn, $inserP);
and I come across this error after submitting the form with the username tom:
pg_query(): Query failed: ERROR: column "tom" does not exist LINE 2: SET name=tom
Here is my form
<form action="update.php" method="post">
<input type="text" name="username" id="username" autocomplete="off" />
<input type="image" name="confirm" src="/images/confirm.png"/>
</form>
Here is my update.php
require('conn.php');
require('getfacebookapi.php');
$userid = idx($facebook->api('/me/'), 'id', string);
$username=$_POST['username'];
$pszz = "UPDATE particular
SET name=$username
WHERE id=$userid";
if(preg_match("/^[a-zA-Z]+$/", $username)) {
pg_query($conn, $pszz);}
There is absolutely nothing wrong with my pg_pconnect.. Can someone tell me where I went wrong and how to fix this error? I'm new to both php and sql... Thanks!!
Never, never compose SQL statements by string concatenation or interpolation. Use bind parameters (PDO or at least pg_query_params).
You need to put quotes around your strings values, otherwise it will think it's a column.
SET name='tom'
WHERE id='someid'
name is a text field; inserting into text fields requires single-quotes around the value: 'tom'