SQL Query insert error - php

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.

Related

PHP - Unable to use data from database & Internal server error

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.

PHP - MySql Database info not storing

I have been trying to figure this out for hours, I have created a database ( MySql/PHPMyadmin) and i am trying to get user input stored to be able to call back up, however the info is not making it/ saving it to the database, everything shows up okay except this part of code:
$registered = mysqli_affected_rows ($dbc);
echo $registered. "Row is affected";
when run gives me a display of -1 row, I believe this to be a big part of the problem as everything else seems to work okay. I am a complete beginner so could you guys tell me how the best way of debugging this is.
$dbc = $dbc = mysqli_connect ($hostname, $username, $password, $dbname) OR die("Could not Connect");
To input the data to the db i have the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$comments = $_POST ['Comments'];
if (!empty ($comments)){
include ('mysqldb.php');
mysqli_query ($dbc,"INSERT INTO 'User-Comments' (Comments) VALUES ('$comments')");
$registered = mysqli_affected_rows ($dbc);
echo $registered. "Row is affected";
}else {
echo "Nothing Submitted";
}
}
The line:
mysqli_query ($dbc,"INSERT INTO 'User-Comments' (Comments) VALUES ('$comments')");
should be:
mysqli_query ($dbc,"INSERT INTO `User-Comments` (Comments) VALUES ('$comments')");
Notice the change in the apostrophe character ( ` ) around your table name.
An excerpt from the documentation for function mysqli_stmt_affected_rows(): -1 indicates that the query has returned an error.
You should check the value returned by mysqli_query(). If it returns FALSE then you can get details about the reason (error message) by using function mysqli_error().

Warning: mysqli_query(): Couldn't fetch mysqli in C:\ ... on line 13

although this question has been asked (and answered) many times, I didn't find a solution to the problem.
Here is my code:
<?php
#session_start();
include("./include/config.php");
include("./include/db_connect.php");
include("functions.php");
if (!isset($_GET['artikelID'])){$_GET['artikelID'] = "";}
if (!isset($_SESSION['UserID'])){$_SESSION['UserID'] = "";}
$sql = "SELECT kundenID FROM kunden WHERE username = '".$_POST['myusername']."' AND password = '".md5($_POST['mypassword'])."' ";
$result = mysqli_query($connect, $sql) OR die("<pre>\n".$sql."</pre>\n".mysqli_connect_error()); // this is line 13
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result)==1){
doLogin($row['kundenID'], isset($_POST['Autologin']));
header("location:cart.php?action=add&artikelID=".$_GET['artikelID']."&id=". $_SESSION['UserID'] ." ");
}
else {
header("location:k_login.php?error=TRUE ");
}
include("./include/db_close.php");
?>
mysqli_connect_error() shows me the absolute correct sql-query; the sql-query is tested with a tool named mysql-front and brings exactly one (and the correct one) result, which is 'kundenID'.
I have tested many things (like $_SESSION['connect'] or $_GLOBALS['connect'] instead of $connect in db_connect.db), but with no result.
Can anyone please help me?
-- Update --
Why does nobody answer?
Is the description of the problem unclear?
The db-connection is established like this:
<?php
error_reporting(E_ALL);
$connect = mysqli_connect($dbserver,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Zeile ".__LINE__.": Datenbankverbindung ist fehlgeschlagen ! " . mysqli_connect_error();
exit();
}
?>
All the db-variables are known in the checklogin-script (tested). All the $_POST-variables are also known in the checklogin-script (tested). I even tried a hard-coded sql-query (with the real data of the test-record in the db).
The result is still the same: mysqli_connect_error() reports the correct query - but then nothing more happens.
I have spent more than 10 hours in the meantime. I really would appreciate, if someone could help me.
Couldn't fetch mysqli means that PHP is unable to identify the contents of your $connect variable as a valid mysqli connection. Try adding some error handling into "./include/db_connect.php" to get an idea of what happened to the mysqli connection that is preventing you from using it.

php inserting into a MySQL data field

I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);

Write to MYSQL table not working

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.

Categories