I'm trying to create a website (similar to pastebin) that allows a user to submit text on the homepage, which then takes them to a randomly generated url (domain.com/ABCXYZ) that is running run.php, which will then display the original content they submitted.
Once a user submits the form their input userentry is added to the database (column userinput). The randomly generated url code idgen (so a random code like KmdpV) is added to the randomurl column in the database.
This much is working without issue (successfully takes users to a randomly generated URL and the adds the userentry and idgen to the database.
However, two issues are popping up that I can't seem to solve:-
I keep getting a 500 internal server error (seems to be caused by something within the else if (isset...) statement in the run.php code below. The error it keeps giving is GET http://example.com/WsnNp 500 (Internal Server Error) (where WsnNp is any randomly generate code) Failed to load resource: the server responded with a status of 500 (Internal Server Error).
For some reason, I can't seem to access the userentry data at all. Once the form is submitted, it is succesfully added to the database and succesfully takes me to a random url running run.php, but it won't display anything if I write <?php echo $_GET['userentry'] ?> (nor using POST, nor using SELECT ... FROM database etc.).
Being able to access the userentry on the randomly generated page is key for the entire site. The userinput needs to be permenantly available on that randomly generated URL, so for example, if I have the database row:
ID | userinput | randurl |
102 | Hello world | GdksQ |
Then I'm trying to make it so that if a user visits example.com/GdksQ then it would display Hello world
I've already attempted grabbing the data from the database etc., but all my attempts seem to lead back to the 500 internal server error.
<?php $endurl = $_POST['idgen']; ?>
<?php
if (isset($_POST['userentry'])) {
// servername, username, password, dbname here
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO mydatabasename (userinput,randurl)
VALUES ('$_POST[userentry]','$_POST[idgen]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
header('Location: http://example.com/'.$endurl);
}
The if part of this statement (above) seems to be working, because as mentioned, it does insert the values into the database, and it does take you to a random url after you submit the form (but I still can't display userentry nor idgen, even if I write it outside of this statement.
else if (isset($_GET['idgen'])) {
// servername, username, password, dbname here
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT userinput FROM mydatabasename WHERE randurl = '".$_GET[idgen]."'";
$result = $db->query($sql);
if ($result) {
if ($row = $result->fetch_object()) {
echo($row['userinput']); }
$result->close() ; }
$conn->close(); } ?>
As far as I've been able to narrow it down, it's the above else if statement that's causing the 500 internal server error. Although I'm not sure if this is also what's preventing me from displaying / using the userinput?
<form action="/run.php" method="POST">
<input type="hidden" name="idgen" value="<?php echo $randomGen ?>">
<input type="text" name="userentry">
<input type="submit">
</form>
($randomGen is just a function that generates a random 5 letter id for use in the url)
RewriteRule ^([0-9a-zA-Z]+)$ run.php?idgen=$1 [L]
This is the RewriteRule that allows me to use random urls and still run run.php on those pages.
EDIT:
Having checked the error logs, it seems the issue is stemming from this line:
$result = $db->query($sql); as it says PHP Fatal error: Call to a member function query() on null in /home/mycpanelname/public_html/run.php on line 46.
There's also some PHP Notices, but mainly seem to be undefined variables etc.
Related
I am currently working on a project which will sell a product to a user, and on checkout completion, the user will enter an email address. I have been trying (but to no avail so far) to use MySQL to put this data into a database. Only in a certain way. I need the input data to use the UPDATE method to be put into an already existing row. This row should match the following criteria. It should not have already been used, the email should not already exist within the database. I have tried so many different pieces of MySQL, I get all sorts from syntax errors to it updating every record in my table, I have gotten as far as it updating just one, but not checking if it already exists. I was hoping for a little insight as to how I can improve!
Code as follows:
<?php
$servername = "localhost";
$username = "Josh";
$password = "10584066";
$dbname = "customers";
// Get email address from input form
$Email = $_GET['keyword'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE list SET Email='$Email' , In_Use='1' WHERE In_Use='0' LIMIT 1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
header('Location: /liteservers/logon/wood.php');
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
So, as you can see. The code is working almost as intended, I just want it to also check to see IF the email is already in the database and if it is, perhaps add the time that it attempted to record a new email within the same row as the already found existing email. I hope this actually makes sense if you need any more info that I haven't provided, let me know!
Use INSERT ON DUPLICATE KEY UPDATE syntax and mysql_affected_rows will tell you if its and insert or update.
I have a web page created in php using html code. I want to save user information entered in my web page to a MySQL database. I am using php as the middle man to link the frontend web page(htmnl code) to the database(mysql).
Inside my link folder (middle man php file) I have the following:
<?php
//Gets server connection credentials stored in serConCred2.php
require_once('ConCred2.php');
//SQL code for connection w/ error control
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(!$con){
die('Could not connect: ' . mysqli_connect_error());
}
//Selection of the databse w/ error control
$db_selected = mysqli_select_db($con, DB_NAME);
if(!$db_selected){
die('Can not use ' . DB_NAME . ': ' . mysqli_error($con));
}
//Co-PI and Co-Investigator Information variables
$Co_FNAME = $_POST['fname'];
$Co_LNAME = $_POST['lname'];
$Co_SLNAME = $_POST['slname'];
$Co_DEGREE = $_POST['Degree_Selection'];
$Co_DEGREE_Other = $_POST['other_specify_degree']; //hold the value of degree if user selected other from the dropdown menu
$Co_CPOS = $_POST['Current_Position_Selection'];
$Co_CPOS_Other = $_POST['other_specify_cpos']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_INST = $_POST['Institution_Selection'];
$Co_INST_Other = $_POST['other_specify_inst']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_SCHOOL = $_POST['School_Selection'];
$Co_SCHOOL_Other = $_POST['other_specify_school']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_DEPART = $_POST['Department_Selection']; //Este se estara eliminando en la version online
$Co_DEPART_Other = $_POST['other_specify_department']; //hold the value of Department if user selected other from the dropdown menu
$Co_PROGRAM = $_POST['program'];
$Co_EMAIL = $_POST['email'];
$Co_PHONE = $_POST['phone'];
//If decition when user select other from the dropdown menu
if($Co_DEGREE == "other_degree") $Co_DEGREE = $Co_DEGREE_Other;
if($Co_CPOS == "other_cpos") $Co_CPOS = $Co_CPOS_Other;
if($Co_INST == "other_inst") $Co_INST = $Co_INST_Other;
if($Co_SCHOOL == "other_school") $Co_SCHOOL = $Co_SCHOOL_Other;
if($Co_DEPART_Other == "other_department") $Co_DEPART = $Co_DEPART_Other;
//This sets a starting point in the rollback process in case of errors along the code
$success = true; //Flag to determine success of transaction
//start transaction
echo "<br>1. Going to set autocommit to 0";
$command = "SET AUTOCOMMIT = 0";
echo "<br>2. Autocomint has been set to 0";
echo "<br>3. Going to run query to see if result is true or false";
$result = mysqli_query($con, $command);
echo "<br>4. Finished running the query. Result is:" . $result;
echo "<br>5. Going to set command to BEGIN";
$command = "BEGIN";
echo "<br>6. Command is now BEGIN";
echo "<br>7. Going to run query for command BEGIN";
$result = mysqli_query($con, $command);
echo "<br>8. Query runned for command BEGIN";
echo "<br>9. Result value is: " . $result;
//Saves Pi values into database
/**
$sqlCoPI = "INSERT INTO co_pi_table (Fname, Lname, SLname, Degree, Current_Position, Institution, School, Department, Program, Email, Phone)
VALUES('$Co_FNAME', '$Co_LNAME', '$Co_SLNAME', '$Co_DEGREE', '$Co_CPOS', '$Co_INST', '$Co_SCHOOL', '$Co_DEPART', '$Co_PROGRAM', '$Co_EMAIL', '$Co_PHONE')";
*/
echo "<br>10. Going to write sql command to populate table pi_table";
/**
$sqlPi = "INSERT INTO pi_table (Fname, Lname, SLname, Degree, Current_Position, Institution, School, Department, Program, Email, Phone)
VALUES('$Co_FNAME', '$Co_LNAME', '$Co_SLNAME', '$Co_DEGREE', '$Co_CPOS', '$Co_INST', '$Co_SCHOOL', '$Co_DEPART', '$Co_PROGRAM', '$Co_EMAIL', '$Co_PHONE')";
*/
$sqlPi = "INSERT INTO pi_table (Fname) VALUES('$Co_FNAME')";
//Checks to see if theres an error in the pi db con
echo "<br>11. Sql command finished writting.";
echo "<br>12. Going to query the sql finished command to the database to determine value of result.";
$result = mysqli_query($con, $sqlPi);
echo "<br>13. Finished running sql command to database. Result value is: " . $result;
echo "<br>14. Going to enter if statements depending on result value";
if($result == false){
//die ('<br>Error in query to PI table: ' . mysqli_error($con));
echo "<br>15. I am inside the false statement. Success is going to be set as false. ";
$success = false;
//$success = true; //Cahnged this in order to test if values are being saved to db. Change back to false.
}
//Checks for errors or craches inside the code
// If found, execute rollback
echo "<br>16. Going to verify is success is true.";
if($success){
$command = "COMMIT";
$result = mysqli_query($con, $command);
//echo "<br>Tables have been saved with 0 errors.";
echo "<br><p style=\"color: red;\"Principal Investigator has been saved successfuly. <br><br>
You may now CLOSE this page and press the<br><br> \"Refresh List\" <br><br>
button to display name in dropdown menu selection.</p>";
}
else{
$command = "ROLLBACK";
$result = mysqli_query($con, $command);
echo "<br>17. Success was determined to be false.";
echo "<br>Error! Databases could not be saved.<br>
Contact system manager to report error. <br> <br>" . mysqli_error($con);
}
echo "<br>18. Setting autocommit back to 1 again.";
$command = "SET AUTOCOMMIT = 1"; //return to autocommit
$result = mysqli_query($con, $command);
//Displays message
//echo '<br>Connection Successfully. ';
//echo '<br>Database have been saved';
//Close the sql connection to dababase
mysqli_close($con)
?>
As you can read, I am requiring users to fill out their information. Some of the information required are dropdown menu fields that user selects an option from among the presented ones.
The problem I am having is, when the above php code executes, it determines that the $result variable is false and doesn't save anything. When you execute the code, you get the following messages displayed:
1. Going to set autocommit to 0
2. Autocomint has been set to 0
3. Going to run query to see if result is true or false
4. Finished running the query. Result is:1
5. Going to set command to BEGIN
6. Command is now BEGIN
7. Going to run query for command BEGIN
8. Query runned for command BEGIN
9. Result value is: 1
10. Going to write sql command to populate table pi_table
11. Sql command finished writting.
12. Going to query the sql finished command to the database to determine value of result.
13. Finished running sql command to database. Result value is:
14. Going to enter if statements depending on result value
15. I am inside the false statement. Success is going to be set as false.
16. Going to verify is success is true.
17. Success was determined to be false.
Error! Databases could not be saved.
Contact system manager to report error.
18. Setting autocommit back to 1 again.
For security purposes I cant post the html content since it has sensitive name information nor the databases. Although I can ensure that the tables inside the database are called exactly as mentioned in the sql command line.
I HAVE FOUND THE PROBLEM!
After long debating I decided to recreate the database In which all the information was being stored. When I redirected the table in my sql command ( Instead of saving it in "pi_table" I saved it in a newly created database called "pi_table_2") and everything worked out properly.
Aparently my database got corrupted and phpMyAdmin didn't recognized that it was curropted.
For reference my database tables where in InnoDB format. What might have cause this to happen, who knows but if you ever encounter a similar problem, creating a small testing database and see if it saves. If it does, recreate the table and it might solve your issue like it solved mine.
Once again thank you a lot guys!!!!!
I am looking at the code and everything seems to be in order, could be a syntax error like a missing quotation for example:
//SQL code for connection w/ error control
$con = mysqli_connect("DB_HOST", "DB_USER", "DB_PASSWORD", "DB_NAME");
also
$db_selected = mysqli_select_db($con, "DB_NAME");
or die ("Cant select Database");
}
Hope this help.
Cheers;
Hasan
So I'm currently trying to establish a database connection to my server and my insertion is having some problems. My query works when I manually try to plug it into phpmyadmin and a single row gets inserted.
However, when I try to load a page with the below code, it seems to hit the database 3 times. I tried using exit() right after my query to see if there was any weird loops, but it still got entered 3 times into the database. Is there anything that seems weird here?
//timestamp
$t = time();
$stamp = date("Y-m-d", $t);
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check connection
if($conn->connect_error){
die("connection failed: ".$conn->connect_error);
}
echo "Connection Successful"."<br>";
$name = "hi";
$affiliation = "yo";
$note = "wat";
$sql = "INSERT INTO `$table` (`name`, `affiliation`, `notes`, `timestamp`) VALUES ('$name', '$affiliation', '$note', '$stamp')";
$result = $conn->query($sql);
if($result){
echo "Data entered successfully";
echo "<br>".$sql;
} else{
echo "Error: " .$sql."<br>".$conn->error;
}
$conn->close();
MORE INFO*****
So here is a sample output for the whole table during one session
id: 281 - Name: yo wat 2016-09-03 19:18:09
id: 282 - Name: yo wat 2016-09-03 19:18:11
id: 283 - Name: yo wat 2016-09-03 19:18:11
id: 284 - Name: yo wat 2016-09-03 19:20:55
As you can tell by the timestamp, one gets added in one session and it is correct. However, shortly after that one is added 2 more instances of the query are run and put in. So the reason I was seeing 3 outputs per refresh is because of the 2 extra inserts that get through. (The 2 extra + the 1 correct insert)
I'm mystified as to why it does this, because it seems to be a server-related issue. I'm running mariadb and things look correct, but maybe something isn't closing correctly?
I don't think this is a fix to the problem since I wasn't able to directly get it working, but using a separate html file to submit a form with post.php I was able to get correct results (1 entry). The reason why the page itself adds 3 entries per refresh is still unknown, but what I am doing now is something satisfactory.
I would like to know if someone knows a reason to why this happens, but for now, the immediate problem is solved.
I've spent today going through tons of similar questions and trying to figure out what is wrong with my code, lots of issues people had with back ticks, quotes, etc but none seem to help or change my cause. My code is no producing any errors, but when I use echo to print out my query results, it seems that the id is not getting a value.
In my delete.php:
<?
ini_set('display_errors',"1");
$username="xxx";
$password="xxx";
$database="xxx";
$conn = new mysqli(localhost, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = (int)$_GET['number'];
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id."");
$conn->close();
?>
And the delete button in my main.php (the rest of the php is correctly displaying my table with data):
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
Can someone help pick out what is causing my rows not to delete when I hit the delete button that I have created, or maybe something that more clearly can help me debug? (I don't want to use checkboxes for this).
EDIT:
I also tried this code (while defining the function as $sql and I'm getting a "Success" message:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
EDIT 2:
I changed the structure following the advice that I should use POST, thinking I might have caught something I didn't notice before, but still not working.
echo "<td><form method='post' action='delete.php'>
<input type='hidden' name='row_id' value=".$row['id']." />
<input type='submit' name='delete_row' />
</form>";
-
if(isset($_POST['delete_row'])) {
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");
$stmt->bind_param('i', $_REQUEST['row_id']);
$stmt->execute();
}
If I do it the above way, nothing happens. Also tried this way, and get a syntax error:
if(isset($_POST['delete_row'])) {
$id = $_POST['row_id'];
$sql = "DELETE FROM tourdates WHERE id=".$id;
mysqli_query($conn,$sql);
}
A potential problem that I can see, is that you are not quoting localhost so php will look for a constant called localhost:
$conn = new mysqli('localhost', $username, $password, $database);
^ ^ here
You are also not checking for errors so that is why you don't see any. The easiest way to fix that, is to have mysqli throw exceptions. Just add this to the top of your script:
mysqli_report(MYSQLI_REPORT_STRICT);
I also don't know if you can mix procedural and object oriented mysqli like that. You should probably stick to the OOP version.
Apart from that you should not use a link (GET request) for your delete actions. What if a web-crawler or a browser extension tries to fetch the links? Instead you should use a POST request (like a form with a button).
Edit: There is another problem which causes you not to get your ID and as you cast it to int, you will always get 0:
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
^ Oooops, closing the href attribute value here...
Your id gets placed after the value / outside of the quote of the href value. You can easily verify this if you look at the source of your page.
You need:
<td><a href='delete.php?number=".$row['id']."'>Delete</a></td>
Replace these two parts of code in your php file, first write your host in the quotations
$conn = new mysqli('localhost', $username, $password, $database);
in your where condition you wrote id=".$id."" replace it with id=".$id
write it as:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id);
Edited:
If you want to see error in your query then use the below code:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id) or die(mysqli_error($conn));
why not use try and catch to see your error?
anyways try this
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");<br>
$stmt->bind_param('i', $_REQUEST['number']);<br>
$stmt->execute();
could this be the problem ?
$id = (int)$_GET['number'];
May be this would be better... ?
$id = intval($_GET['number']);
Anyway if, echo($query) print an empty id, this is probably because your parameter is not an integer.
I am trying to write to a MySQL Database / Table with the following code - but for some reason it just won't write! I've changed the "INSERT INTO" line quite a few times, trying different things each time - no luck!!!
The DBsettings.php contains variables with the MySQL connection info - which worked for creating the tables and setting the column types and stuff. For your information, it is running the main code (there are no errors with the user info entered), and echoing "Awesome! No errors!", so I'm not too sure what's not working - the MySQL checking line is saying that I'm able to connect properly... Can someone look over my code?
The PasswordHash.php file contains code for hashing and salting passwords - nothing to see here, got it from another site, no errors at all.
I know I'm not 'cleansing' the MySQL code for more security...
if($error == null){
include('DBsettings.php');
$connect = mysqli_connect($dbserver, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Failed to connect to MySQL Database! Error: '.mysqli_connect_error();
} else {
include('PasswordHash.php');
$passinfo = explode(':', create_hash($password));
$addinfo = "INSERT INTO {$dbprefix}Users (Email, Displayname, Registered, Rank, Status, Password, Salt) VALUES ('{$email}', '{$displayname}', '{date('Y\/m\/d')}', 9999, 1, '{$passinfo[3]}', '{$passinfo[2]}')";
/* format: algorithm:iterations:salt:hash */
mysqli_query($connect, $addinfo);
mysqli_close($connect);
echo 'Salt: '.$passinfo[2];
echo '<br>Hash: '.$passinfo[3];
echo '<br>Awesome! No Errors!';
}
} else {
echo $error;
}
That's the code in question - I've tried adding;
error_reporting(E_ALL);
ini_set('display_errors', '1');
But all that reveals is undefined localhost errors in my DBsettings.php file - and the file worked when I created the MySQL DB tables, so I don't really have that as a priority.
Thanks!
If you echo your query, you will notice this issue. Following is your final query
INSERT INTO Users (Email, Displayname, Registered, Rank,Status, Password, Salt)
VALUES ('', '', '{date('Y\/m\/d')}', 9999, 1, '', '')
Notice that your date was not interpolated like you expected it to, and i'm sure if you have that field in MySQL set as a datetime field, it wont accept that value {date('Y\/m\/d')}, Move the date function call outside the string.
Plus you are not getting any error after the query execution because you are simply not checking for one. One example how to check for that can be
if (!mysqli_query($connect, $addinfo)) {
printf("Error: %s\n", mysqli_error($connect));
}
I saw your INSERT query contains this '{date('Y/m/d')}' ,maybe the single quotes has conflict,You'd better escaping the date('Y/m/d') statement's single quotes.