Trying to follow a tutorial, but i get a database error on line six of the executable php file (second code below)
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_select_db("beyondmotors");//add your dbname
$sql = "select * from `TestTable` where ID = 1";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['FName'];
$lname = $row['LName'];
$phone = $row['PHON'];
//we will echo these into the proper fields
}
mysql_free_result($query);
?>
<html>
<head>
<title>Edit User Info</title>
</head>
<body>
<form action="updateinfo.php" method="post">
userid:<br/>
<input type="text" value="<?php echo $id;?>" name="id" disabled/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $fname;?>" name="fname"/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $lname;?>" name="lname"/>
<br/>
Phone Number:<br/>
<input type="text" value="<?php echo $phone;?>" name="phon"/>
</br>
<input type="submit" value="submit changes"/>
</form>
</body>
</html>
and here is the executable
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_se lect_db("beyondmotors");//add your dbname
//get the variables we transmitted from the form
$id = $_POST[''];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phon = $_POST['phon'];
//replace TestTable with the name of your table
$sql = "UPDATE `TestTable` SET `FName` = '$fname',`LName` = '$lname',
`PHON` = '$phon' WHERE `TestTable`.`ID` = '$id' LIMIT 1";
mysql_query($sql) or die ("Error: ".mysql_error());
echo "Database updated. <a href='editinfo.php'>Return to edit info</a>";
?>
everything is good until i hit submit changes; than i get error on line 6. I'm new to database so please be specific if possible. Thank you! also if anyone could point me to a similar, "working" tutorial that would help ALOT!
trying to follow this tutorial: http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php
i'm using wamp server, so the database log in is correct. I mean it displays the data, just doesn't edit it..
The error i'm getting is :
Notice: Undefined index: ID in C:\wamp\www\test\updateinfo.php on line 6
i get that even if i change post to $id = $_POST['ID'];
Ok I changed the $_POST['']; to $_POST['id']; , still had the same error.
Than I read online to add a # to the front so now it looks like this: #$_POST['id'];
That too off all the errors. but not my data base is not been updated. Everything goes through with no errors but no data is been changed??
Also when i tried to remove backticks I get this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\test\updateinfo.php on line 12
So i left them the way they were...
Could it be because i'm using a local server? This should be all simple not sure what i'm doing wrong here.. I mean i literary copied everything over from the tutorial.
First and foremost, you should be warned that your code is completely vulnerable against sql injections. Escaping your POST data before inserting it into the database is a good start in protecting your database.
Also, learning the mysql extension is useless for new systems because it is deprecated. You might think about looking into the PDO interface or the mysqli extension. There are many beginner tutorials for both and you will gain much more.
Now, as for your error
Make sure you are defining which ID you want to update in your database. In your second block of code you have:
//get the variables we transmitted from the form
$id = $_POST[''];
needs to change to:
$id = $_POST['id'];
You said you get the error even if you change post to $id = $_POST['ID'], but if you look at your form, the id input has name = 'id' and PHP is case sensitive.
Now, in your sql query, all of those back ticks are unnecessary. Also, there is no point in specifying which table ID because this is all being done in ONE table, TestTable.
//replace TestTable with the name of your table
$sql = "UPDATE TestTable SET FName = '$fname',LName = '$lname',
PHON = '$phon' WHERE ID = '$id' LIMIT 1";
EDIT:
Although the query above is syntactically correct, you should consider using mysqli or PDO due to reasons mentioned above. Below are examples using mysqli and PDO.
Mysqli
mysqli Manual
/* connect to the database */
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* build prepared statement */
$stmt = $mysqli->prepare("UPDATE TestTable SET FName=?, LName=?, PHON=? WHERE ID=?)");
/* bind your parameters */
$stmt->bind_param('sssi', $fname, $lname, $phon, $id);
/* execute prepared statement */
$stmt->execute();
/* close connection */
$stmt->close();
PDO
PDO Manual
/* connect to the database */
$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $pass);
/* build prepared statement */
$stmt = $dbh->prepare("UPDATE TestTable SET FName = :fname, LName = :lname, PHON = :phon WHERE ID = :id");
/* bind your parameters */
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->bindParam(':phon', $phon);
$stmt->bindParam(':id', $id);
/* update one row */
$fname = 'John'; # or use your $_POST data
$lname = 'Doe';
$phon = '123-456-7890';
$id = 1;
/* execute prepared statement */
$stmt->execute();
/* use it again!1! */
$fname = 'Jane';
$lname = 'Doe';
$phon = '123-456-7890';
$id = 2;
/* execute prepared statement */
$stmt->execute();
/* close connection */
$dbh = null;
Remove backticks:
UPDATE TestTable SET FName = '$fname',LName = '$lname',PHON ='$phon'
WHERE TestTable.ID = '$id' LIMIT 1";
Related
I have tested everything and nothing works here's my code
<?php
session_start();
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) { die('Invalid id'); }
$conn = mysqli_connect("redacted", "redacted", "redacted", "redacted");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$id = (int)$_GET['id'];
"UPDATE affiliate SET clicks WHERE ID='$id' = clicks + 1";
header("Location: https://discord.gg/CjzZRBq");
?>
and after I want it to echo on the users dashboard this is what I have
<h1>Clicks</h1>
<br />
<br />
You have gotten: <?php $conn = mysqli_connect("localhost",
"id2278622_jonny", "Fencing1", "id2278622_affiliate");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
$sql = "SELECT clicks FROM affiliate WHERE ID='$ID'";
echo "$sql";
?> Clicks!
but it just echos the sql code
You haven't actually sent your query to the database. You've just built a query string. A string that you didn't even save to a variable.
$id = (int)$_GET['id'];
"UPDATE affiliate SET clicks WHERE ID='$id' = clicks + 1";
header("Location: https://discord.gg/CjzZRBq");
Should be:
$id = (int)$_GET['id'];
$qry= "UPDATE affiliate SET clicks = clicks+1 WHERE ID='$id'";
conn->query($qry);
header("Location: https://discord.gg/CjzZRBq");
You should also look up SQL Injection. Casting to an int mitigates risk, but you should definitely be using bind variables.
The problem is you're just echoing $sql (which is the query string), rather than passing that SQL command to your database. Also note that your current script is vulnerable to SQL injection. To avoid this, use prepared statements:
// Retrieve the number of existing clicks
$stmt = $conn->prepare("SELECT clicks FROM affiliate WHERE ID = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($clicks); // Store the result in the $clicks variable
$clicks++; // Increment clicks
// Update the table
$stmt2 = $conn->prepare("UPDATE affiliate SET clicks = ? WHERE ID = ?");
$stmt2->bind_param("si", $clicks, $id);
$stmt2->execute();
// Close the connection once finished
$conn->close();
Hope this helps! :)
looked around, saw a lot of MySQL answers but not MySQLi..
Im attempting to return 1 line of my choosing.
at the moment I can return only the first line.
What im trying to get to is, have my main database be linked by ID, when you click the ID, a closer look at the record is on another page..
<?php
$connect = mysqli_connect("localhost", "root", "", "mydb");
$query = "SELECT name, surname FROM info ORDER BY id";
$record = mysqli_query($connect, $query);
#$num_results = mysqli_num_rows($record);
$row = mysqli_fetch_assoc($record);
$fname = $row['name'];
$surname = $row['surname'];
print $fname;
print $surname;
?>
In order to do what you're asking, first create a list of users:
$connect = mysqli_connect("localhost", "root", "", "mydb");
$query = "SELECT name, surname FROM info ORDER BY id";
$record = mysqli_query($query, $connect);
while($row = mysqli_fetch_assoc($record)){
$user = $row['name'] . ' ' . $row['surname'];
echo '' .$user . '</br>';
}
The will create a list of all your users which look like:
Bart Simpson</br>
Matt Damon</br>
And so on.
When you click the user's link in the original page, it should be processed by the code in user.php:
$connect = mysqli_connect("localhost", "root", "", "mydb");
$query = "SELECT name, surname FROM info WHERE id = ?"; // returns one line identified by id - you can use something else if you're guarateed the value is unique in your table
$stmt = mysqli_prepare($connect, $query);
mysqli_stmt_bind_param($stmt, 'i', $_GET['uid']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name, $surname);
mysqli_stmt_fetch($stmt);
I'll bet you can guess what happens now, can't you? That's right, you can echo out the data for the individual user on this page:
$user = $name . ' ' . $surname;
echo $user;
NOTES:
The connection code could be placed in a separate file and included in pages where needed.
You could write a function to handle every query you write.
In order to prevent the possibility of SQL Injection I have used prepared statements for MySQLi. Even escaping the string is not safe!
Generally I would be a lot more consistent with my coding, performing queries the same way each and every time. doing so will reduce troubleshooting time as well as making your code easier for others to read.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I'm building a recruiting website and need to save user data in my database but my form isn't sending anything to the database in phpmyadmin (using WAMP).
I checked the error logs for PHP, MySQL and Apache but don't see any errors. I also added "if/echo" blocks inside the $conn variables to test the connection, which returned true. Code below.
<!-- index.html-->
<form action="process.php" method="post">
<input type="text" name="first_name" placeholder="First Name" /><br/>
<input type="text" name="last_name" placeholder="Last Name" /><br/>
<button type="submit" name="submit"></button>
</form>
//database.php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "xxxx";
$dberror1 = "Could not connect to the database!";
$dberror2 = "Could not find selected table!";
// Connection to the database, Already tried this with echo statement and works
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
// Selecting the database to connect to
$select_db = mysqli_select_db($conn, 'mainbase') or die ($dberror2);
//process.php
<?php include 'database.php';
if(isset($_POST['submit'])) {
// Creating variables to store form values
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
//Executing the query
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name') //Values in 'candidates' table on phpmyadmin
VALUES ('$first_name','$last_name')");/*variables from above*/
}
You're using myqli incorrectly. But on top of that, use PDO to connect to your database instead. It's safer and easy to expand in the future. Here is an example of how to connect to your database with PDO.
<?php
$myUser = "XXXXXX";
$myPass = "XXXXXX";
try{
$dbPDO = new PDO('mysql:host=localhost;dbname=xxxxxxxx', $myUser, $myPass);
$dbPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection was successful";
} catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br />";
die();
}
?>
Simply change the Xs to your server's settings.
When you want to start a query simply you can do it like so:
$query = $dbPDO->prepare("SELECT * FROM Table_Name");
$query->execute();
Of course you'd want to pass variables to your queries so you can do that like this:
$query = $dbPDO->prepare("SELECT * FROM Table_Name WHERE ID = :id");
$query->bindParam(':id', $id);
$query->execute();
That keeps SQL injection off your worries. Just make sure to sanitize your variables before binding them to the query as well.
I figured I'd show how to insert your variables into your table with PDO.
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (:fname, :lname)");
$query->bindParam(':fname', $firstName);
$query->bindParam(':lname', $lastName);
$query->execute();
You could also make an array of both of your POST variables and pass that instead of binding each variable at a time.
$candidateName = array('$_POST['first_name']', '$_POST['last_name']');
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (?, ?)");
$query->execute($candidateName);
I hope that helps!
Happy coding!
The problem
Don't put table name and column names between apostrophes. That's what's causing your query to fail. Apostrophes are used to pass strings.
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name')
VALUES ('$first_name','$last_name')");
Should be
mysqli_query($conn, " INSERT INTO candidates(first_name, last_name)
VALUES ('$first_name','$last_name')");
Or
mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if you like it better.
The error handling
In order to verify the problem you can echo the mysqli_error() function result whenever the query fails, it's a nice practice and would probably have helped you find a solution faster than asking it here.
$query= mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if(!$query) //the query will return 0 if it fails
{
echo mysqli_error($conn);
}
The security issue
You're adding POST value directly into your query, which is dangerous.
On these lines:
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
You should be escaping user input.
This will escape any special characters that can cause issues in the mysql query.
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
I am working with php and mysql for the first time. The goal is to have a table that store email addresses to form a mailing list for a newsletter. my table Emails has 2 columns ID (INT auto increment) and email (varchar, 255)
I can connect to the database but I cannot write to it. I think my problem is in the syntax of my INSERT INTO statement. I have seen many examples and they seem to use different syntax specifically around the values.
form code:
<form method="post" action="email.php" class="form-container">
<div class="form-title"><h2>Sign up for my newsletter!</h2></div>
<div class="form-title">Email Address</div>
<input class="form-field" required="required" placeholder="example#mail.com" type="text" name="newEmail" /><br />
<div class="submit-container">
<input class="submit-button" type="submit" value="Submit" /></div>
</form>
php code:
<?php
$dbHost = "localhost";
$dbUser = "input";
$dbPass = "input";
$dbName = "MailingList";
$conn= mysqli_connect ($dbHost, $dbUser, $dbPass, $dbName);
if(mysqli_connect_errno()) {
die("FAIL:". mysqli_connect_error() . "(" . mysqli_connect_errno() . ")");
}
$addEmail = "mysqli_real_escape_string($_POST['newEmail'])";
$query ="INSERT INTO Emails (email) VALUES ('$addEmail')"
mysqli_close($conn)
?>
You have missed to add the $conn i.e database link to the mysqli_real_escape_string and also, you have wrapped the mysqli_real_escape_string() inside the ", so it consider as string. So remove the " and use it. Try this,
$addEmail = mysqli_real_escape_string($conn,$_POST['newEmail']);
......^
$query ="INSERT INTO Emails (email) VALUES ('$addEmail')";
instead of
$addEmail = "mysqli_real_escape_string($_POST['newEmail'])";
You need to execute the query, not just write it.
$query ="INSERT INTO Emails (email) VALUES ('$addEmail')";
mysqli_query($conn, $query);
If you use a prepared statement, you can save yourself the trouble of escaping:
$stmt = mysqli_prepare($conn, "INSERT INTO Emails (email) VALUES (?)");
mysqli_stmt_bind_param($stmt, "s", $_POST['newEmail']);
mysqli_stmt_execute($stmt);
If you want non-procedural style (aka oop), this would look like the following
$stmt = $conn->prepare("INSERT INTO Emails (email) VALUES (?)");
$stmt->bind_param("s", $_POST['newEmail']);
$stmt->execute();
Get rid of the quotes around your escape function. This turns it into a string instead of actually escaping the value:
$addEmail = mysqli_real_escape_string($conn,$_POST['newEmail']);
$addEmail = mysqli_real_escape_string($conn,$_POST['newEmail']);
http://in2.php.net/mysqli_real_escape_string
string mysqli_real_escape_string ( mysqli $link , string $escapestr )
Ok so essentially what I'm trying to do is add a q&a component to my website (first website, so my current php knowledge is minimal). I have the html page where the user's input is recorded, and added to the database, but then I'm having trouble pulling that specific info from the database.
My current php page is pulling info where the questiondetail = the question detail (detail='$detail') in the database, but that could potentially present a problem if two users enter the same information as their question details (unlikely, but still possible, especially if the same person accidentally submits the question twice). What I want to do is have the page load according to the database's question_id (primary key) which is the only thing that will always be unique.
HTML CODE:
<form id="question_outline" action="process.php" method="get">
<p><textarea name="title" id="title_layout" type="text" placeholder="Question Title" ></textarea> </p>
<textarea name="detail" id= "detail_layout" type="text" placeholder="Question Details" ></textarea>
<div id="break"> </div>
<input id="submit_form" name="submit_question" value="Submit Question" type="submit" />
</form>
PROCESS.PHP CODE:
$name2 = $_GET['name2'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$query= "INSERT INTO questions (title, detail) VALUES ('$title', '$detail')";
$result = mysql_query("SELECT * FROM questions where detail='$detail' ")
or die(mysql_error());
The info is being stored correctly in the database, and is being pulled out successfully when detail=$detail, but what I'm looking to do is have it pulled out according to the question_id because that is the only value that will always be unique. Any response will be greatly appreciated!
Updated Version
QUESTION_EXAMPLE.PHP CODE
<?php
$server_name = "my_servername";
$db_user_name ="my_username";
$db_password = "my_password";
$database = "my_database";
$submit = $_GET['submit'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$conn = mysql_connect($server_name, $db_user_name, $db_password);
mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT title, detail FROM questions WHERE id =" .
mysql_real_escape_string($_GET["id"]), $conn);
$row = mysql_fetch_assoc($result);
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Firstly, if that is code to be used in production, please make sure you are escaping your SQL parameters before plugging them in to your statement. Nobody enjoys a SQL injection attack. I would recommend using PDO instead as it supports prepared statements and parameter binding which is much much safer.
How can I prevent SQL injection in PHP?
So you have a form...
[title]
[details]
[submit]
And that gets inserted into your database...
INSERT INTO questions (title, details) VALUES (?, ?)
You can get the last insert id using mysql_insert_id, http://php.net/manual/en/function.mysql-insert-id.php.
$id = mysql_insert_id();
Then you can get the record...
SELECT title, details FROM questions WHERE id = ?
And output it in a preview page.
I have written an example using PDO instead of the basic mysql functions.
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$pdo = new PDO("mysql:dbname=test");
// Prepare the insert statement and bind parameters
$stmt = $pdo->prepare("INSERT INTO questions (title, detail) VALUES (?, ?)");
$stmt->bindValue(1, $_POST["title"], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST["detail"], PDO::PARAM_STR);
// Execute the insert statement
$stmt->execute();
// Retrieve the id
$id = $stmt->lastInsertId();
// Prepare a select statement and bind the id parameter
$stmt = $pdo->prepare("SELECT title, detail FROM questions WHERE id = ?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
// Execute the select statement
$stmt->execute();
// Retrieve the record as an associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Without PDO...
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute the insert statement safely
mysql_query("INSERT INTO questions (title, detail) VALUES ('" .
mysql_real_escape_string($_POST["title"]) . "','" .
mysql_real_escape_string($_POST["detail"]) . "')", $conn);
// Retrieve the id
$id = mysql_insert_id($conn);
// Close the connection
mysql_close($conn);
header("Location: question_preview.php?id=$id");
question_preview.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute a select statement safely
$result = mysql_query("SELECT title, detail FROM questions WHERE id = " .
mysql_real_escape_string($_GET["id"]), $conn);
// Retrieve the record as an associative array
$row = mysql_fetch_assoc($result);
// Close the connection
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
I assume you want to sort the questions according to the question_id. You could try using the ORDER BY command
example -
$result = mysql_query("SELECT * FROM questions where detail='$detail' ORDER BY question_id")
For these type of examples, you need to run Transaction within database
below are the
http://dev.mysql.com/doc/refman/5.0/en/commit.html
Or else
Create an random variable stored in session and also insert into database and you call it from database and you can preview it easily.
id | question_code | q_title
question_code is the random value generated before insertion into database,
and save the question_code in a session and again call it for preview.