I have basic PHP/MySQL experience, having taken an introductory class. My knowledge is literally limited to the following PHP codes:
if(!($stmt = $mysqli->prepare...)
if(!($stmt->bind_param...)
if(!$stmt->execute...)
I'm currently trying to write a program that allows a user to enter a new password, and checks the password against existing passwords in the database.
Here is what I have:
<?php
foreach($Password){
$dupesql = "SELECT PasswordID Passwords WHERE (Password = '$Password')";
$duperaw = mysql_query($dupesql);
if(mysql_num_rows($duperaw){
echo nl2br("$Password has already been used \n");
}
else{
echo "Password added \n";
}
}
?>
I got the code from this post: Check for duplicates before inserting
I'm not sure if the code itself has problems or if I need to add anything else to my PHP code to get this working, as it's currently producing an "Error 500".
MySQL extension is deprecated and probably you have PHP 7.0 from where it is removed. Rewrite your code to MySQLi or PDO. Check this question on how to convert to MySQLi: How could I change this mysql to mysqli?
Also, your code just doesn't add a password (never). Probably you expect to add it before the "Password Added" message, but be aware: the solution you want to use is not ideal, because there is a risk of race condition between checking the password for existence and adding it. This means that it is possible to add a password twice.
To solve this problem, you might want to use transactions. More details are covered in this question: PHP + MySQL transactions examples
I decided to go an entirely different route, which is to set the Password column as unique.
Then I did a simple INSERT that would prompt an error if the user attempts to add a duplicate:
<?php
if(!($stmt = $mysqli->prepare("INSERT INTO Heroes(HeroName, FirstName, LastName, Age, HomeCountry, RoleID) VALUES (?,?,?,?,?,?)"))){
echo "Prepare failed: " . $stmt->errno . " " . $stmt->error;
}
if(!($stmt->bind_param("sssisi",$_POST['HeroName'],$_POST['FirstName'],$_POST['LastName'],$_POST['Age'],$_POST['HomeCountry'],$_POST['RoleID']))){
echo "Bind failed: " . $stmt->errno . " " . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: " . $stmt->errno . " " . $stmt->error;
} else {
echo "Added " . $stmt->affected_rows . " row to Heroes.";
}
?>
Related
I am following the last part of the following video tutorial "How to create a database website with PHP and mySQL 07 - Add in input form" :
https://www.youtube.com/watch?v=MGIG00d1Xzc&list=PLhPyEFL5u-i0zEaDF0IPLYvm8zOKnz70r&index=7
At the end here is my code, for the inserting portion to the database for the new_jokes.php script (everything up to this point of the series I have gotten to work fine so far)
Basically I am getting the seemingly classic "INSERT INTO" not working although all my syntax looks correct. Am I missing something obvious here? I get no errors, just the row isn't added.
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question
$new_joke_answer </h2>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES
(NULL, '$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
include "search_all_jokes.php";
?>
Return to the main page
Here is the db_connect.php code as requested:
<?php
// four variables to connect the database
$host = "localhost";
$username = "root";
$user_pass = "usbw";
$database = "test";
// create a database connection instance
$mysqli = new mysqli($host, $username, $user_pass, $database);
?>
Here is search_all_jokes.php (which has minor error checking):
// if there are any values in the table, select them one at a time
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "SELECT JokeID, Joke_question, Joke_answer FROM Jokes_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "JokeID: " . $row["JokeID"]. " - Joke_question: " .
$row["Joke_question"]. " " . $row["Joke_answer"]. "<br>";
}
} else {
echo "0 results";
}
?>
Also here is the table structure screenshot viewed in myPHPAdmin:
I added error capturing into new_jokes.php inspired by this Stack Overflow post:
INSERT INTO SYNTAX ERROR
And get the following error:
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 't jump.' )' at line 1localhost via TCP/IP
Thank you everyone for helping out with this! Syntax can really throw a wrench in everything. I also will read up on prepared statements since that also could have prevented the issue. The ultimate help to this I found the solution to by adding the function referenced here for MySQLi real_escape_string to clean the single quote I had within the answer I was submitting to my joke table:
(Can a kangaroo jump higher than the empire state building? Of course, the empire state building can't jump.)
As shown in the documentation #miken32 linked as a comment here it is says: "But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)"
But now the code for this part 7 of the tutorial on you tube I found works and adds it into a row on the database table, then displaying the full new table on the next webpage. I spent a good while shooting in the dark on while the answer ended up being fairly simple. Again special thanks to #miken32 for pointing me the right direction.
Here is my completed code that ended up working to at least achieve the goal of the tutorial:
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
$new_joke_question = $mysqli->real_escape_string($new_joke_question);
$new_joke_answer = $mysqli->real_escape_string($new_joke_answer);
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question $new_joke_answer
</h2>";
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES (' ',
'$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
if ($mysqli->query($sql) === TRUE) {
echo 'users entry saved successfully';
}
else {
echo 'Error: '. $mysqli->error .'<br>';
}
include "search_all_jokes.php";
?>
Return to the main page
I am using PHP to pass a query like this:
"UPDATE `prove750_mrdias`.`stringsMrDias`
SET `conteudo` = '$conteudo'
WHERE `stringsMrDias`.`ID` = $id;"
when I echo $conteudo I get Sobre\nmim as expected.
But after the query, I look at the database and the value stored is the formatted string:
'sobre
mim'
That's causing all sorts of problems when parsing the data back to my application.
If I go to phpMyAdmin and pass the value of $conteudo manually it maintains the expected behavior, only when querying the replace is happening without calling it.
Any ideas?
I suspect it's an issue of interpolation. You can kill two birds with one stone by using prepared statements. By using prepared statements
your data won't be corrupted or need to be manually handled by you,
your application will not be subject to security issues a la SQL injection.
This might look like:
$sql = "UPDATE `prove750_mrdias`.`stringsMrDias` SET `conteudo` = ? WHERE `stringsMrDias`.`ID` = ?";
$preparedStatement = $pdo_handle->prepare( $sql );
$preparedStatement->execute([$conteudo, $id]);
That is, you first tell the database the form of the query you want executed, and then -- in a separate call -- you send the arguments to that query.
Try http://php.net/manual/en/function.nl2br.php
Example,
$conteudo = nl2br($conteudo);
Then store into database.
Prepared statements was the right direction.
After looking at the mysqli documentation I ended up with a code like this:
`$sql = "UPDATE `prove750_mrdias`.`stringsMrDias` SET `conteudo` = (?) WHERE `stringsMrDias`.`ID` = (?)";
if (!($stmt = $con->prepare($sql))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param('ss', $conteudo,$id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}`
Had to use the bind_param() as execute() don't accept any parameters.
I have a SQL string that updates my DB
I have left out most of the insert code as this is not where I need help. I run the string updating numerous tables but I need to stop the string once an error is detected.
I have in the first SQL string a Unique coulomb that i do not want duplicates of but in the other tables duplicates of the same coulomb doesn't matter. As this is history tables keeping history of the objects
This section is the sql section thereafter I start the sql 1
if ($conn->query($sql) === TRUE) {
echo "Client and Unit has been loaded ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error in uploading information";
}
$sql1 = "INSERT INTO unit_history SET
The error is correct and the table is not populated but it goes on to the next sql1 string I need it to stop once the error is found.
Duplicate entry '111' for key 'unitnr'
Notice: Undefined variable: con in client_rep.php on line 120
Is there a way I can Kill the script once error is noted on duplicate entry?
If you want to stop execution only then use die(); or exit();
Or
You can return from there:
if ($conn->query($sql) === TRUE) {
echo "Client and Unit has been loaded ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error in uploading information";
die; // Use die or exit here.
}
if (!$mysqli->query("UPDATE custom_fav SET credits = credits + 1 WHERE user_id = $current")) {
echo "Credit addition failed: (" . $mysqli->errno . ") " . $mysqli->error;
} else {
echo 'hi';
}
Does anybody know why the mysqli query keeps running twice?
I am getting 1 of the echo statements but I am getting + 2 added to the database instead of 1.
For example i changed it to 5 and it added 10 into the database.
Most likely you are calling this script twice. It this script called via home-brewed SEO-friendly URL? Do not make it act as a 404 handler then.
I'm a complete beginner at PHP but have managed a simple code to input data to a table.
The code is:
$query = "INSERT into $table (suggestion1) VALUES('$suggestion1')";
All works fine but if the data inserted contains an apostrophe (e.g. don't) the query fails.
I've searched for hours but the answers I get are beyond my knowledge.
Any help or pointers would be great!
Steven
What you should be looking are prepared statements, in which to write your queries with parameters, and the call that prepared statement passing in parameters values and let the driver make the replaces/escaping. Here's a good starting point using mysqli.
Here's a simplified code sample from PHP.net :
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
You want to escape your input: check the documentation.
Basically, what happens is this: when you put that data in with quotes, you get this:
INSERT INTO $table (suggestion1) VALUES ('it's great');
and MySQL gets confused with the second quote. When you "escape" you get this:
INSERT INTO $table (suggestion1) VALUES ('it\'s great');
and MySQL knows that second quote is part of the data, not of the query.
Wikipedia has info on it as well (a little more extensive, but worth reading and understanding).