PHP INSERT INTO MySQL not working, no error given - php

I am currently trying to execute an INSERT INTO when a search button is clicked. Eventually I'd like to submit the search term into the database, however I'm currently just trying to submit a simple string to ensure the initial INSERT INTO works correctly, which it currently doesn't.
I have the following:
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="search" name="search" id="results" placeholder="Enter search">
<input type="submit" name="submit" class="frstBtn" value="searchterm"><br>
</form>
<?php
$searchterm = "";
?>
<?php
if(isset($_POST['submit']))
{
$sql = "INSERT INTO tableName (variableName) VALUES ('test')";
$results = mysqli_query($conn,$sql) or die(mysqli_error());
}
?>
The latter php function, search, works perfectly fine, but the former function including the INSERT INTO does not.
Here is the table itself in phpmyadmin.
I have successfully manually copied and pasted the actual INSERT INTO statement into the actual database and it has worked fine, so I know the issue isn't with the statement. Any help is much appreciated. Thanks.

Since the searchTerm column is defined as PRIMARY, I’m ready to bet that you are trying to insert the same value twice and you don't have enabled the error_reporting. To find out exactly what the problem is, first of all enable all errors by adding the following at the beginning of your script:
ini_set('error_reporting', -1);
ini_set('display_errors', 1);
Also, note that you must use mysqli_error($conn) instead of mysqli_error().
By the way, to ignore errors when inserting unique values, use:
INSERT IGNORE INTO searchHistory(searchTerm) VALUES ('test')

Related

PHP insert data into SQL Database Table produces blank row

I'm trying to insert data from the form created into the SQL Server Database Table that is connected through ODBC. After I submit the data it shows up as a blank row with only the ID that has a value. I am very new to PHP and got parts of code from tutorials. This is just a test project. Here's the code:
<html>
<header>
<title>
</title>
</header>
<body>
<form action="\INSERTCODE.php" method="POST">
<input type= "number" step="any" name="sepal_lengp" placeholder="Sepal Length">
<input type= "number" step="any" name="sepal_widthp" placeholder="Sepal Width">
<input type= "number" step="any" name="petal_lengp" placeholder="Petal Length">
<input type= "number" step="any" name="petal_widthp" placeholder="Petal Width">
<input type= "text" name="flower_type" placeholder="Flower Name">
<button type="submit" name="submit" >INPUT VALUES</button>
</form>
<?php
//display all results from table
include("C:\Users\Dshop\Desktop\php-7.3.3\Server1\connection.php");
$i=1;
$sql = "SELECT * FROM dbo.textcsv";
$result = odbc_exec( $connection, $sql );
while($all =odbc_result_all($result,$i) ){
echo $all;
}
?>
</body>
</html>
This part includes the form. The filename is index1.php.
<?php
include("C:\Users\Dshop\Desktop\php-7.3.3\Server1\connection.php");
$sepal_lengp = $_POST['sepal_lengp']??'';
$sepal_widthp = $_POST['sepal_widthp']??'';
$petal_lengp = $_POST['petal_lengp']??'';
$petal_widthp = $_POST['petal_widthp']??'';
$flower_typep = $_POST['flower_typep']??'';
$dbinsert = "INSERT INTO dbo.textcsv (sepal_leng, sepal_width, petal_leng, petal_width, flower_type) VALUES ('$sepal_lengp', '$sepal_widthp', '$petal_lengp', '$petal_widthp', '$flower_typep');";
odbc_exec( $connection, $dbinsert );
HEADER("Location: ../index1.php?=success");
This part inserts data into the database table, using $_POST to obtain the data from index1.php. This file is called INSERTCODE.php. $connection and connection.php is the file that includes the connection to ODBC.
For this test project I used the Iris dataset. I believe that I had to use ODBC and SQL Server instead of mysql. Sql server is the 2014 version, PHP is 7.33, using node.js to run the server. Help is greatly appreciated!
EDIT I found out that the $_POST isn't getting any values from the form. Any ideas?
EDIT 2 I've tried using $_REQUEST, checking var_dump, and did all that stuff, but I still got nothing. After going to https://www.w3schools.com/php7/php7_forms.asp for an example form, I found out that the example did not work either. Now i'm not sure if the problem is from the code, or from something like the php configuration. Need help, please help.
you're treating your variables as strings, by th look of your database you want them as floats. Try using floatval( ) (http://php.net/manual/en/function.floatval.php) on your variables to make sure they are in the write format, this will also go some way to sanitising them until you update this to prepare statements so you can safely bind the values and specify the type
After rephrasing my issue to "node.js not taking post data" I found the issue. Node.js needs extra steps to process POST data. So, because of this, my input was ignored by node.js and the INSERTDATA.php ran without any data to insert anything. Turns out the solution of the problem was to use something like the body-parser or the other solution from another question.
The solution I took was to uninstall node.js and use XAMPP instead. It was much easier to use.
Also could someone flag my question for duplicate?

Why PHP inserts multiple rows to MySQL from one single data entry?

I have an HTML code that creates a template to collect 5 variables. These variables are posted to a php that process the info and forward it to a mySQL database.
Following is the HTML template:
<html>
<head>
</head>
<body>
<form action="insert.php" method="post">
<p>Value1 <input type="text" name="value1" /></p>
<p>Value2 <input type="text" name="value2" /></p>
<p>Value3 <input type="text" name="value3" /></p>
<p>Value4 <input type="text" name="value4" /></p>
<p>Value5 <input type="text" name="value5" /></p>
<input type="Submit" />
</form>
</body>
</html>
And here is the PHP form that interacts with MySQL (note that the # are substituted with the actual values in the original form):
<?php
$server="#####";
$username="#####";
$password="######";
$database="#####";
$val1=$_POST['value1'];
$val2=$_POST['value2'];
$val3=$_POST['value3'];
$val4=$_POST['value4'];
$val5=$_POST['value5'];
$con = new mysqli($server,$username,$password,$database);
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= "INSERT INTO test_table (value1, value2, value3, value4, value5) VALUES ('$val1','$val2','$val3','$val4','$val5')";
if (mysqli_query($con, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
mysqli_close($con);
?>
The two forms seem to work fine and there are no errors popping out. The problem is that when I switch to the mysql prompt and interrogate the database to see if it works it shows multiple entry rows instead of only one.
I am pretty confident that the issue is not related to the database's table which was previously created. Just in case I am posting the code I used to create the table.
mysql> create table test_table (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
value1 VARCHAR(10),
value2 VARCHAR(10),
value3 VARCHAR(10),
value4 VARCHAR(10),
value5 VARCHAR(10))
;
So for example, if I load the html form and I insert "a" "b" "c" "d" and "e" in the fields the output should be only 1 record in the mysql. Instead I get two.(I cannot post a picture of the output cause I do not have enough experience point). I have been trying to fix that but I couldn't find where the problem is.
Any help is greatly appreciated.
There's nothing in your code that would create a duplication. One form, if handled once by your PHP code would generate only one row on the db as you know, so either you are posting to a file and then importing another that handles the form more than once or you have some weird redirect going on.
For "a" "b" "c" "d" and "e" to be registered twice (two rows) the form contents are being sent twice to that PHP.
First, try to find out if you are submitting only once:
- In firefox install Live HTTP Headers, capture the POST and see if it goes just once;
Are you using jquery to validate or handle the form submit? if so are you preventing the normal event to occur? If not you might get the data posted twice, one by ajax and the other by normal browser post.
When you refresh your form you still have your POST variables stored from previous entry. Refreshing your browser (in chrome as far as I know) resubmits your POST variables. That is why you seem to get double entries.
In the case you didn't find an answer for this, as none of the answers are marked as a solution, I was having the same issue on my machine today, but it was inserting two random rows and the actual row I was inserting. The bizarre thing is, I was getting multiple entries even giving a single insert instruction on the php interactive mode. Not satisfied, I went directly to mysql console to see what would happen, and, instead of getting one entry I was getting the same three as before. So, the problem was on MySQL and what I thought was trying to drop the table and create it again... It magically solved my problem.

Can't write to Joomla Database?

I am using Joomla 3.0 (it is up to date), and sorcerer. I have a form that I want to submit the entered data to a table in the database that I created. For some reason it will not write to the table, and I am pretty sure it can't find the database.
Since I am using sorcerer, I don't need to include code to connect to the database, it is supposed to be done automatically. I have tried countless variations of code and nothing is working. This seems like it should be pretty simple.
I am new to PHP/SQL coding, so maybe there is something wrong with my code, but after trying so many different things, I am wondering if there is another reason I can't write to the table.
Here is my HTML form and php. Essentially, I want to check if the username entered here in the form exists in the users table in my database. If it does exist and the checkbox is on, enter the username and message into the out_of_office table. If the checkbox is unchecked, delete the row from the table. But, as of now I can't even write to the table, so I figured I should get that part working properly first.
<form method="post" action="">
<p>Out of Office <input name="onoff" type="checkbox" value="ON"></p>
<p><label>Custom Out of Office Message</label>
<input type="text" name="custommessage" size="30" maxlength="25"/></p>
<p><label>Enter Username</label>
<input type="text" name="enterusername" size="30" maxlength="25"/></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
<?php
$username = $_POST['enterusername'];
$message = $_POST['custommessage'];
$query = "INSERT INTO out_of_office VALUES ('$username', '$message')";
mysql_query($query) or die ('Error');
echo "data entered";
?>
When I go to the page on my web site I get a white page that says "Error".
Like I said, I have tried a lot of code for the PHP but nothing works. Please help!
Right, rather than having all your code in an article, you should make a small module which you can then import into your article.
Here is the documentation on how to develop a basic module. In addition to this, you can also use a module generator
Once you have yourself a basic module, you're going to want to start using Joomla coding standards for getting $_POST data. Have a read of the following on how to do this:
http://docs.joomla.org/Inserting,_Updating_and_Removing_data_using_JDatabase
As for your database query, again, you will need to looking into specific coding standards. Read more about this here:
http://docs.joomla.org/Inserting,_Updating_and_Removing_data_using_JDatabase
Here is an example of what your database query would look like
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$columns = array('username', 'message');
$values = array($db->quote($username), $db->quote($message));
$query
->insert($db->quoteName('out_of_office'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$db->setQuery($query);
$db->execute();
Just something to get you started off. Good luck.
Hope this helps

PHP-Function call

I designed plain html site,with one enquiry form.It has some fields like name ,address etc.
Onclick of submit button,i wanted this data to go into the database.
I created database and table using phpmyadmin on XAMPP server.
My code is as follows(hello.php):
<script>
function insert_db()
{
<?php
$username = $_POST['name'];
print ($username);
mysql_connect("localhost","root","");
mysql_select_db("addressbook");
mysql_query("insert into colleague values ('$username')");
?>
}
</script>
<form method="post">
<input type="name" name="name" /><br />
<input type="submit" name="mysubmit" value="Submit" onclick="insert_db()"/>
On click of submit button ,two entries are made into the database.One is blank and other is entered value.
how to call the function only once??Is there any other way out..
You cannot, I repeat CANNOT, combine JS and PHP in this way.
Right-click the page, select View Source, and you will clearly see why.
PHP is run BEFORE the browser gets the page.
Therefore, you get an empty record when you load the form, then a filled one when you submit it because $username is defined that time.
You can't mix php and javascript like this. You see, the PHP will always be executed server-side, regardless where it is in the file (PHP does not know JavaScript). Therefore, the first time you load the page, it will insert an empty row (since $_POST['name'] is empty). Then, if you click submit, it will do nothing, since the JavaScript code ist empty, submit the form to the server and evaluate the PHP code again, this time with the desired effect.
A proper way to do this would be:
<?php
if (!empty($_POST['name'])){ // check if form values are there
$username = $_POST['name'];
print ($username);
mysql_connect("localhost","root","");
mysql_select_db("addressbook");
mysql_query("insert into colleague values ('$username')");
}
?>
<form method="post">
<input type="name" name="name" /><br />
<input type="submit" name="mysubmit" value="Submit" />
</form>
You might also want to work your way through a PHP Tutorial first

why when trying to inport to database more than 500 char i get error?

i have items in database but why when i am trying to import more than 500 char from a textarea i have error, the datatype of the field is TEXT
here is part of the the form
<?php
//query to get the $ProductDesc and some other codes then
echo "<textarea name='p_desc' id='p_desc' class='input' rows='10' cols='53'>$ProductDesc</textarea>";
?>
then the form post in the same page, then i get the value like this:
$a4 = $_REQUEST['p_desc'];
then i am trying to (update or add) the record,
i have error while importing, and it didn't take effect in updating
and this is my update query
mysql_query("UPDATE product SET ProductDesc='$a4' WHERE ProductID = $productID ");
please help and thanks in advanced, the error in PHP or what?
the form header:
<form name="myform" action="add-product.php" method="post" enctype="multipart/form-data">
am using enctype="multipart/form-data" because i upload images also every thing is good with exception of the textarea
Before your query add
$a4 = mysql_real_escape_string($a4);
In fact, you should call this function on any user-specified value going into a query. Not only can you produce errors such as what you have seen, but if were to specify the description as
'; DROP TABLE product; --
then you'd really be in trouble. This is known as SQL injection and is something you should be very careful of.
How do you have your ProductDesc field set up? is it varchar, mediumtext, longtext? I always use longtext and I have never had any problems with over 500 chars. Post your form, maybe you need to strip some characters out of the Description before it is submitted to the database.
and there was a little hiccup in there :D
instead of
<?php
//query to get the $ProductDesc
<textarea name='p_desc' id='p_desc' class='input' rows='10' cols='53'>$ProductDesc</textarea>
?>
use
<?php
//query to get the $ProductDesc
echo "<textarea name='p_desc' id='p_desc' class='input' rows='10' cols='53'>".$ProductDesc."</textarea>";
?>
and to fix the update or add function rewrite it so it checks if it is already there or not, then on a if statement add your query or update functions.
And when you hit submit on your form you have now what error does it tell you?!?

Categories