so i have this key giveaway script, now i want to get the displayed key deleted from the database. how do i get this to work within the code i wrote?
so $key is the key that will be send to you and display in the browser, but i want this key to get deleted out of the database after it is send and displayed so it cannot get shown a second time to another user.
<?php
//fill in mail
echo "
<form method='post' action=" . $_SERVER['PHP_SELF'] . ">
Email: <input name='email'></input><br>
<input type='submit' value='Get your key' name='submit'> </input><br><br>
</form>";
if(empty($_POST["email"]))
{
echo "Please enter an email adress.";
}
else{
// get key from database
$key = dispres();
//mail key to input mail
$to = $_POST["email"];
$subject = 'Your test key';
$message = 'Your key is: ' . $key;
$headers = 'There you go!';
mail($to, $subject, $message, $headers);
echo "Your code has been sent to your email: " . $_POST["email"] . " \r";
echo $key;
}
function dispres(){
//database connect
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'pwd';
$database = 'c3keys';
$table = 'test';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
//grab random key from database
$result = mysql_query("SELECT * FROM {$table} order by RAND() LIMIT 1");
$row = mysql_fetch_row($result);
$result = implode('|',$row);
return $result;
//delete key from database
//had this as a begin
mysqli_query("DELETE FROM test WHERE test='$key'");
//remember ip adress for 1 use only
}
?>
1- you're using both mysql and mysqli stick with one...
2- your delete query is after the return so it will never run.
3- what is $key? I don't see where you set it.
4- STOP USING mysql_* these functions are deprecated. Use mysqli or PDO with prepared statements.
Explanation point 1:
In your code at the beginning of your dispres function, you have mysql_connect, mysql_select_db and mysql_query at the end for your delete query you used mysqli_query notice the i in the last function, you can't use mysqli here, as you had connected with mysql adapter.
Explanation point 2:
You have return $result; then after that you have mysqli_query("..."); PHP won't execute that line of code because for PHP and any other programming language when they see a return this means the function is done, nothing more to do, so you can't have any line that you want executed after the return
Explanation point 3:
In your whole dispres function there isn't $key so basically $key is empty, I think you mean using $result in that query. And even if you use $result your delete won't work, because $result is a string where you joined all your fields into it and added | pipe sign between each one and the other. so column test will never be equal to your $result. You should replace $key by the actual value of the test column you want to delete maybe like this:
$row = mysql_fetch_row($result);
$test_i_want_to_delete=$row[0];//Where 0 is the number of column of `test` in your db table, starting counting from 0
$result = implode('|',$row);
mysql_query("DELETE FROM test WHERE test='$test_i_want_to_delete'");
Explanation point 4:
If you're just starting to learn PHP it would be much better for you not to learn any deprecated functions that will be totally removed in future releases. So at the place of using mysql_* functions, take a look at PDO or mysqli, and especially look at how to use prepared statements.
I hope my answer helps clear out some stuff.
Related
I'm trying to convert some php code that uses mysql into mysqli code. I'm not sure why it doesn't work - I didn't write the original code and am not that comfortable with the hash part of it, and it seems to be where the issue is. As I show in the code below, the "error" part gets echo'ed so it's something to do with the hash strings, but I don't really understand why changing to mysqli has broken the code. Both versions of the code are below, and the original code works. I deleted the variables (host name, etc.) but otherwise this is the code I am working with.
Mysql Code:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysql_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysql_connect_error());
mysql_select_db($db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysql_real_escape_string($_GET['name'], $db_link);
$score = mysql_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "insert into scores values (NULL, '$name', '$score');";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
}
Mysqli code (doesn't work):
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysqli_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysqli_connect_error());
mysqli_select_db($db_link, $db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysqli_real_escape_string($_GET['name'], $db_link);
$score = mysqli_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "INSERT INTO `scores` VALUES (NULL, '$name', '$score');";
$result = mysqli_query($db_link, $query) or die('Query failed: ' . mysqli_error($db_link));
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
mysqli_close($db_link); //close the database connection
One notable "gotchu" is that the argument order is not the same between mysql_real_escape_string and mysqli_real_escape_string, so you need to swap those arguments in your conversion.
$name = mysqli_real_escape_string($db_link, $_GET['name']);
$score = mysqli_real_escape_string($db_link, $_GET['score']);
It's good that you're taking the time to convert, though do convert fully to the object-oriented interface if mysqli is what you want to use:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
// Enable exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli($host_name, $user_name, $password);
$db->select_db($db_name);
return $db;
}
$db = db_connect(""); //connect to the database using db_connect function
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $_GET['hash']) {
// Don't include ; inside queries run through PHP, that's only
// necessary when using interactive MySQL shells.
// Specify the columns you're inserting into, don't leave them ambiguous
// ALWAYS use prepared statements with placeholder values
$stmt = $db->prepare("INSERT INTO `scores` (name, score) VALUES (?, ?)");
$stmt->bind_param("ss", $_GET['name'], $_GET['score']);
$result = $stmt->execute();
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
// Should use a connection pool here
$db->close();
The key here is to use prepared statements with placeholder values and to always specify which columns you're actually inserting into. You don't want a minor schema change to completely break your code.
The first step to solving a complex problem is to eliminate all of the mess from the solution so the mistakes become more obvious.
The last if statement is controlling whether the mysql query gets run or not. Since you say this script is echoing "error" form the else portion of that statement, it looks like the hashes don't match.
The $hash variable is getting passed in on the URL string in $_GET['hash']. I suggest echo'ing $_GET['hash'] and $real_hash (after its computed by the call to MD5) and verify that they're not identical strings.
My hunch is that the $secretKey value doesn't match the key that's being used to generate the hash that's passed in in $_GET['hash']. As the comment there hints at, the $secretKey value has to match the value that's used in the Javascript, or the hashes won't match.
Also, you may find that there's a difference in Javascript's md5 implementation compared to PHP's. They may be encoding the same input but are returning slightly different hashes.
Edit: It could also be a character encoding difference between Javascript and PHP, so the input strings are seen as different (thus generating different hashes). See: identical md5 for JS and PHP and Generate the same MD5 using javascript and PHP.
You're also using the values of $name and $score after they've been escaped though mysqli_real_string_escape, so I'd suggest making sure Javascript portion is handling that escaping as well (so the input strings match) and that the msqli escape function is still behaving identically to the previous version. I'd suggest echo'ing the values of $name and $score and make sure they match what the Javascript side is using too. If you're running the newer code on a different server, you may need to set the character set to match the old server. See the "default character set" warning at http://php.net/manual/en/mysqli.real-escape-string.php.
im trying to update date on the table. YYYY-MM-DD HH-MM-SS.
There is the code i have.
It takes information from table and after that I want it to set date in that table to current time
<?php
$username = "root";
$password = "sawasq";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$code = $_POST['kodas'];
$code = stripslashes($code);
$sql = mysql_query("SELECT * FROM dviraciai WHERE ID='$code'");
$Pavadinimas = 'Pavadinimas';
$Metai = 'Metai';
$Status = 'Status';
$rows = mysql_fetch_assoc($sql);
echo 'Pavadinimas: ' . $rows[$Pavadinimas] . '<br>';
echo 'Metai: ' . $rows[$Metai] . '<br>';
echo 'Status: ' . $rows[$Status] . '<br>';
$sql2 = mysql_query("UPDATE Dviraciai WHERE ID='$code' SET date=CONCAT(CURDATE(),' ',time(mytime))");
mysql_close();
?>
I get $code from input.
Dviraciai is my table.
I dont get any error. But when i enter my $code it shows the info but doesnt change time in table after I restart phpMyAdmin
Your query is totally wrong, and since you never bother checking for errors and simply ASSUME nothing could ever go wrong...
Update syntax is
UPDATE ... SET ... WHERE...
You have the set/where reversed. And note that restarting phpmyadmin is beyond pointless. It's a MANAGEMENT INTERFACE. It's not the database itself. It's like trying to change the outcome of a tv show by turning your tv on/off.... the show's going to end up broadcasting the same ending no matter what you to do with your TV.
Never assume success with DB operations. Even if your SQL is 100% syntactically perfect (and yours definitely isn't), there's far too many OTHER reasons for a query to fail. Assuming success is, frankly, just plain stupid. Always assume failure, check for failure, and treat success as a pleasant surprise. At bare minimum, have something like this:
$result = mysql_query(...) or die(mysql_error());
I have problem with code. It works if data in row of Database is present. But if data is not present then also it gives message as 12345-12345-12345-12345(sample key) already registered . use another key.
This is code:
$namecheck = mysql_query("SELECT pkey FROM license_key WHERE pkey ='$userEnteredProductKey'");
if(is_resource($namecheck) && mysql_num_rows($namecheck) > 0 ){
$sql_result = mysql_fetch_assoc($namecheck);
echo $userEnteredProductKey . " already registered . use another key";
}
Please correct me if i go wrong.
First of all before doing anything else please phase out mysql_* functions and switch to use PDO or MySQLi. Especially if your project is dealing with serial keys or some unique keys. As of now your query can be easily hacked by injecting extra SQL
Back to problem:
since it executes echo statement it means that if statement gets executed which means is_resource() and mysql_num_rows() both return true.
why dont you check the database and see again if there exists a record with 12345-12345-12345-12345, seems like mysql_num_rows returns > 0
Also why dont you var_dump $sql_result and see what it prints
It is not advisable to use mysql_query. Try this below.
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_SELECT, DB_PORT);
$stmt = $mysqli->prepare("SELECT pkey FROM license_key WHERE pkey =?");
$stmt->bind_param('s',$userEnteredProductKey) ;
$stmt->execute();
$stmt->bind_result( $pKey );
$stmt->fetch();
$stmt->close();
if($pkey!=''){
echo $userEnteredProductKey . " already registered . use another key";
}
Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);
i want to add records to table 'pool' with attribute ID and empName from database employees
theform.html
<FORM NAME ='form2' METHOD ='POST' ACTION ='result.php' enctype="multipart/form-data">
<B>Board Write</B> <BR>
<INPUT TYPE = Text Name = empID value = 'write ID here'>
<INPUT TYPE = Text Name = empName VALUE = 'write name here'><P>
<INPUT TYPE = 'Submit' Name = Submit2 VALUE = 'Post'>
</FORM>
result.php
<?PHP
$ID = $_POST['empID'];
$NAME = "'" . $_POST['empName'] . "'";
$server = "127.0.0.1"; //connect to server
$user_name = "root";
$password = "";
$database = "employees";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_found){// there is a database
$tableSQL = "INSERT INTO pool(ID, empName) VALUES " . "(" . $ID . "," . $NAME . ")";
$result = mysql_query($tableSQL);
if($result){
print "success!";
}
else{
print "fail!";
}
}
mysql_close($db_handle); //close the connection;
?>
in the database, ID is unique and also an INT datatype, i want to catch the error code where the user inputs an ID value that already existing in the database. how do we do this?
You can use mysql_errno() (or mysqli_errno(), if you use mysqli) to get the error number after a query if it failed (check the return value of mysql_query()). It should be error #1022 (ER_DUP_KEY) according to the mysql error documentation
In general, it is better to prevent SQL errors than to catch them. For example, check whether a duplicate exists before you even try to insert the record.
To avoid the issue altogether, you could use an auto-increment field for the ID, and allow the database to assign new numbers automatically. Then the user would never need to enter it, so there would never be a clash due to duplicates.
If you do still need to check for errors, then you can use the mysql_error() or mysql_errno() functions to get the error details.
// returns true if duplicated
function duplicate_catch_error ($database_connection) {
$mysql_error = array (1022 => "Can't write; duplicate key in table '%s'",1062 => "Duplicate entry '%s' for key %d", 1586 => "Duplicate entry '%s' for key '%s'"); // also allows for the use of sscanf
if (array_key_exists(mysql_error($database_connection),$mysql_error)) // checks if error is in array
return true;
else
return false;
}
hope this answers your question, also mysql is now depreciated. Use mysqli if you didn't already know
:)