Issue trying to insert data into a MySQL table with php - php

I have an existing table and I'm trying to insert data to it from a form submission.
I think I need another set of eyes to look over my code. There is an issue with it, at this point I'm not sure what.
I fill out the form, it appears to submit, I check the table and I get nothing. No data gets inserted.
If some of the values aren't being used right now, can that hinder the data from being inserted into the table? Shouldn't the form inputs that are on the form be inserted anyway? I tried to use only the values within the form, and that still did not work.
For example, right now the form inputs are only for first, last, title, genre, about, and picture. The rest only exist within the table. Data for the remaining fields cannot be currently entered at this time.
Hopefully someone has a solution?
$servername = "server";
$username = "user";
$password = "pass";
$dbname = "db";
if (isset($_POST['submit'])){
$conn = mysqli_connect($servername,$username,$password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
$first = mysqli_real_escape_string($conn, $_POST['First']);
$last = mysqli_real_escape_string($conn, $_POST['Last']);
$title = mysqli_real_escape_string($conn, $_POST['Title']);
$storylink = mysqli_real_escape_string($conn, $_POST['StoryLink']);
$genre = mysqli_real_escape_string($conn, $_POST['Genre']);
$about = mysqli_real_escape_string($conn, $_POST['About']);
$link = mysqli_real_escape_string($conn, $_POST['Link']);
$picture = mysqli_real_escape_string($conn, $_POST['Picture']);
$alt = mysqli_real_escape_string($conn, $_POST['ALT']);
$sql = "INSERT INTO ContrTemp (`First`,`Last`,`Title`,`StoryLink`,`Genre`,`About`,`Link`,`Picture`,`ALT`)
VALUES ('$first','$last','$title','$storylink','$genre','$about','$link','$picture','$alt')";
mysqli_query($conn, $sql) or die('Error: ' . mysqli_error($conn));
mysqli_close($conn);
}
Here is one input field from the form. The others are pretty much the same.
<input type="text" id="ContrTitle" name="Title" placeholder="Title" class="inputFields" style="width:650px;" />
Could there be an issue with the name within the input?
sql table structure:
CREATE TABLE IF NOT EXISTS `ContrTemp` (
`ID` int(5) NOT NULL AUTO_INCREMENT,
`First` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`Last` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`Title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`StoryLink` varchar(140) COLLATE utf8_unicode_ci NOT NULL,
`Genre` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
`About` varchar(2000) COLLATE utf8_unicode_ci NOT NULL,
`Link` varchar(125) COLLATE utf8_unicode_ci NOT NULL,
`Picture` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`ALT` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Now I'm actually hitting the database, a record shows up, but no data was inserted. Before, No record was inserted at all.

You can try this one for inserting data
$sql = 'INSERT INTO ContrTemp (First,Last,Title,StoryLink,Genre,About,Link,Picture,ALT) VALUES ("'.$first.'","'.$last.'","'.$title.'","'.$storylink.'","'.$genre.'","'.$about.'","'.$link.'","'.$picture.'","'.$alt.'")';

I think you have done pretty well but one last try put these symbols [backticks] ` around your fields to understand mysql they are just fields.
$sql = "INSERT INTO ContrTemp (`First`,`Last`,`Title`,`StoryLink`,`Genre`,`About`,`Link`,`Picture`,`ALT`)
VALUES ('$first','$last','$title','$storylink','$genre','$about','$link','$picture','$alt')";

Your mysqli_error() is incorrect syntax, you need to specify the connection so have mysqli_error($conn) to properly feedback to you the SQL errors. As mentioned by Mitkosoft in comments some of your column names are MySQL keywords. It could be a good habit to get into to always encase column names in backticks.
So:
$sql = "INSERT INTO ContrTemp (`First`,`Last`,`Title`,`StoryLink`,`Genre`,`About`,`Link`,`Picture`,`ALT`)
VALUES ('$first','$last','$title','$storylink','$genre','$about','$link','$picture','$alt')";
mysqli_query($conn, $sql) or die('Error: ' . mysqli_error($conn));
Also you don't need to select db with mysqli_select_db($conn,$dbname); because the database is selected on the login command mysqli_connect above.
Further queries:
Is your database access account allowed to INSERT to this database?
Can you insert the same data as in your form directly into the database using an interface such as PHPMyAdmin, MySQL Workbench (Or whichever one you use to view the DB)?

I had hoped this had been as simple as the code I provided above, thus the reason I did not mention that this code was being used as part of a WordPress template. I did not think that would be come an issue as the template is pretty light weight.
With that said, I simply took my block of php code that handles the data insertion, and I placed it at the top of the template. Worked like a charm..

Related

can't insert into database (webservice)

I am creating a web service which will be called from an android app. Actually I am trying to do an insert into my database but i can't figure out why it is not working. Here is my code, with some tests I have made in order to find the bug :
<?php
$con = mysqli_connect("localhost", "xxx", "xxx", "xxx");
/* here is the original code that I commented in order to do my tests
$mail = $_POST["mail"];
$mdp = $_POST["mdp"];
$nom = $_POST["nom"];
$prenom = $_POST["prenom"];
$dateNaissance = $_POST["dateNaissance"];
*/
$mail = "test#mail.fr";
$mdp = "test";
$nom = "test";
$prenom = "test";
$dateNaissance = "2000/01/01";
$statement = mysqli_prepare($con, "INSERT INTO utilisateur (mail, mdp, nom, prenom, dateNaissance) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sssss", $mail, $mdp, $nom, $prenom, $dateNaissance);
mysqli_stmt_execute($statement);
$query = "SELECT * FROM utilisateur";
$result2 = mysqli_query($con, $query);
$final = mysqli_fetch_row($result2);
print_r($final);
?>
The SELECT request returns me the row I have in my utilisateur table so I suppose it's not a problem of connection.
Moreover, mysqli_stmt_execute($statement) returns 1... So if i'm not wrong it's supposed to mean that my request worked ? Anyway, nothing is inserted.
I'm hosting my database with 000webhost, don't know if this will help... I'm starting developing so everything is not crystal clear.
Hope that I was understandable and that you'll enlighten me!
I found what was wrong : everything was working really well... But i was connecting to the wrong database. Indeed I began my project in localhost and then used 000webhost hosting. I got confused since it was written "server : localhost" in the two phpMyAdmin interfaces and also because I had the exact same table in the two databases.
Thanks for the answers that still made me learn.
The query causes this error
Error: Field 'idUser' doesn't have a default value.
You will need to fix your table. Make it an InnoDB table.
CREATE TABLE `utilisateur` (
`idUser` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`mail` VARCHAR(40) COLLATE utf8_bin NOT NULL,
`mdp` VARCHAR(40) COLLATE utf8_bin DEFAULT NULL,
`nom` VARCHAR(40) COLLATE utf8_bin DEFAULT NULL,
`prenom` VARCHAR(30) COLLATE utf8_bin DEFAULT NULL,
`dateNaissance` DATE DEFAULT NULL,
PRIMARY KEY (`idUser`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

form not adding to database after submitting it

I havet a user event form that ive created and it wont add anything to database ive checked all form elements against the database columns and read several other comments on here about this but nothing is happening can someone possibly please check this over for me many thanks in advance jan x
<?php
include ('config/db_connect.php');
include("config/ckh_session.php");
if (isset($_POST['submit'])) {
$event_type = mysqli_real_escape_string($conn, $_POST['event_type']);
$event_date = mysqli_real_escape_string($conn, $_POST['event_date']);
$event_country = mysqli_real_escape_string($conn, $_POST['event_country']);
$event_postcode = mysqli_real_escape_string($conn, $_POST['event_postcode']);
$event_title = mysqli_real_escape_string($conn, $_POST['event_title']);
$event_description = mysqli_real_escape_string($conn, $_POST['event_description']);
$event_ltm = mysqli_real_escape_string($conn, $_POST['event_ltm']);
$query = "INSERT INTO meets (`event_type`,`event_date`,`event_country`,`event_postcode`,`event_title`,`event_description`,`event_ltm`) VALUES ('$event_type','$event_date','$event_country','$event_postcode','$event_title','$event_description','$event_ltm')";
$result = mysqli_query($conn,$query);
} else {
mysqli_close($conn);
}
?>
And here is the database table
CREATE TABLE IF NOT EXISTS `meets` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`event_type` varchar(50) NOT NULL,
`event_date` varchar(50) NOT NULL,
`event_country` varchar(50) NOT NULL,
`event_postcode` varchar(50) NOT NULL,
`event_title` varchar(255) NOT NULL,
`event_description` text NOT NULL,
`event_ltm` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Ok, make sure that in your form inputs, the name attribute matches with the post values that you are getting. Next, make sure that the form action is pointing to the correct php file, and that the form method is POST. Also, ensure that the form is posting the values. Your php to insert into the database is wrapped in an if->isset for the value 'submitted', so I would also ensure that that value is being passed.

MySQL PHP statements is returning junk data included with the records

Lately my newly created tables in a MySQL database are returning "\r\n\r\n\r\n" on my SELECT statements along with the stored data. I don't know where this junk data is coming from because it is not visible in phpMyAdmin. It is happening only in newly created tables, it doesn't happen in old ones.
I used phpMyAdmin to create the table, but here is the exact statement to create it:
CREATE TABLE IF NOT EXISTS `user_analysis` (
`project_ID` int(11) NOT NULL,
`uGroupId` int(11) NOT NULL,
`user_address` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`user_strengths` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`user_weaknesses` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The table information is this:
Type: InnoDB
Collation: utf8_general_ci
Here is the query I'm making:
$query = "SELECT user_strengths FROM user_analysis WHERE `project_ID` = ? AND `uGroupId` = ?";
if($stmt = $mysqli->prepare($query)){
$stmt->bind_param("ii", $this->pID, $this->gID);
$stmt->execute();
$stmt->bind_result($strengths);
$stmt->fetch();
echo $strengths;
}
I also tried not using prepared statements and hard coding the query, but it still returns junk data. I tried like this:
$query = "SELECT user_strengths FROM user_analysis WHERE `project_ID` = '10256' AND `uGroupId` = '10'";
$result = $mysqli->query($query);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
echo "User strengths: " . $row["user_strengths"];
}
I used the answer found here as a temporary fix: Replacing \r\n with PHP
But working around it is not the problem. The problem is that this shouldn't happen to begin with. What could be causing MySQL to return this junk data? Again, the junk data is not visible from phpMyAdmin. I also tried inserting data directly from phpMyAdmin and carefully make sure there was no such thing as "\r\n\r\n\r\n" in what I inserted, but it still returns that junk data along with the records.
Any ideas?

Creating dynamic tables with MySQLi securely

I want to be able to create dynamic tables, for custom user surveys... like survey monkey... how would I go about create something like that?
Because I want to give the ability to the user to create the survey, with different amount of text fields, and different a option fields... I would need to create a custom table for each survey.
Would something like this be possible?
<?php
$table_name = 'survey_'.$_POST['surveyid'];
$query = 'CREATE TABLE ? (
`responseid` INT NOT NULL AUTO_INCREMENT,
`textarea1` TEXT NULL,
`textarea2` TEXT NULL,
`textarea3` VARCHAR(255) NULL,
`drop_down1` VARCHAR(255) NULL,
`drop_down2` VARCHAR(255) NULL,
`bool1` BIT NULL,
`bool2` BIT NULL,
PRIMARY KEY (`responseid`))';
if($stmt = $mysqli->prepare($query)){
$stmt->bind_param('s', $table_name);
$stmt->execute();
$stmt->close();
}else die("Failed to prepare");
?>
The above example comes back with "Failed to prepare", because I don't think I can prepare a table name... is there another work around using mysqli?
if(ctype_digit($_POST['surveyid']) && $_POST['surveyid']>0){
$table_name = 'survey_'.$_POST['surveyid'];
$query = 'CREATE TABLE '.$table_name.' (
`responseid` INT NOT NULL AUTO_INCREMENT,
`textarea1` TEXT NULL,
`textarea2` TEXT NULL,
`textarea3` VARCHAR(255) NULL,
`drop_down1` VARCHAR(255) NULL,
`drop_down2` VARCHAR(255) NULL,
`bool1` BIT NULL,
`bool2` BIT NULL,
PRIMARY KEY (`responseid`))';
I know I can just try to sanitize the $_POST['surveyid'] (like I did above) but I prefer to prepare it if possible.
$table_name = 'survey_'.$_POST['surveyid'];
Do not do the above. It is easy for a hacker to exploit your site if you include $_GET or $_POST data directly in any SQL string.
But you can't use parameters for a table name. A parameter takes the place of a single scalar value only. You can prepare CREATE TABLE but you can't use parameters for identifiers (e.g. table names).
The best practice is to make sure your table name conforms to a rule, for example only the leading portion of a string of numeric digits, up to the maximum length of a MySQL table name:
$table_name = 'survey_' . strspn(trim($_POST['surveyid']), '0123456789', 0, 56);
If you have other rules for a surveyid, then you could use preg_replace():
$table_name = 'survey_' . preg_replace('^(\w+)', '$1', trim($_POST['surveyid']));
It is not possible to prepare a data definition language statement like "CREATE TABLE". I can't find the reference in the MySQL docs that explains this, but I did find a good explanation on the PHP documentation site.

Trouble Inserting a Image Data to LongBlob Field

Total newbie here, please bear with me.
Building a very small personal app that uploads some images and info. I can't figure out why the following PHP/MySQL doesn't add the last insert in the query ($file_data) to my DB's longblob field.
All the other fields in the query insert fine, meaning I tested them one at a time, adding to the query, until I got to the last and then the insert fails. I am able to echo $file_data before the insert and see that the data is there, I've also found that hardcoding a string value for $file_data (i.e $file_data="this will insert") inserts fine... which is frustrating.
So my guesses are there's an error in the reading of the file ($fp fread etc) or that my longblob is setup wrong. File sizes are <16kb, so I'm sure it's not a php.ini issue either.
Any ideas? Thanks.
$boxtype=$_POST['type'];
$title=$_POST['title'];
if(isset($_POST['submit']) && $_FILES['imgfile']['size'] > 0)
{
$filename = $_FILES['imgfile']['name'];
$tmpName = $_FILES['imgfile']['tmp_name'];
$file_size = $_FILES['imgfile']['size'];
$mime_type = $_FILES['imgfile']['type'];
$fp = fopen($tmpName, 'r');
$file_data = fread($fp, filesize($tmpName));
fclose($fp);
$query = "INSERT INTO table
(boxtype,title,filename,mime_type,file_size,file_data)
VALUES
('$boxtype','$title','$filename','$mime_type','$file_size','$file_data')
";
$db = db_connect();
$result = $db->query($query) or die('Error, query failed');
if ($result)
{
echo "<br>Success<br>";
}
}
else die("No Content");
MySQL Table:
CREATE TABLE `port` (
`id` int(2) unsigned zerofill NOT NULL AUTO_INCREMENT,
`boxtype` tinytext COLLATE latin1_general_ci NOT NULL,
`title` varchar(40) CHARACTER SET latin1 NOT NULL,
`filename` varchar(255) COLLATE latin1_general_ci NOT NULL,
`mime_type` varchar(255) COLLATE latin1_general_ci NOT NULL,
`file_size` int(11) NOT NULL,
`file_data` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
Because its a binary, it probably contains values which means its probably throwing a wobble
Try using addslashes on the file_data variable, so it can save it.
The examples I came across while using Google showed that the data was escape either using addslashes or mysql_real_escape_string. Therefor my guess is that this is a crucial part since the $file_data string may contain various characters.
If on windows use fopen($tmpName, 'rb'); and use mysql_escape_string($file_data) .
You'll have to use the mysqli_ functions to create a prepared statement. Here is an example
$sql = 'INSERT INTO Table(boxtype,title,filename,mime_type,file_size,file_data)
VALUES (?,?,?,?,?,?)';
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "ssssib", $boxtype,$title,$filename,$mime_type,$file_size,$file_data);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
This will also prevent against SQL Injection attacks which it appears your code may be vulnerable to. Alternatively, you can use the PDO libraries to create prepared statements.
With PDO, you can do the following.
$sql = 'INSERT INTO Table(boxtype,title,filename,mime_type,file_size,file_data)
VALUES (:boxtype,:title,:filename,:mime_type,:file_size,:file_data)';
$statement = $con->prepare($sql);
$statement->bindParam(':boxtype',$boxtype,PARAM_STR);
$statement->bindParam(':title',$title,PARAM_STR);
$statement->bindParam(':filename',$filename,PARAM_STR);
$statement->bindParam(':mime_type',$mime_type,PARAM_STR);
$statement->bindParam(':file_size',$file_size,PARAM_INT);
$statement->bindParam(':file_data',$file_data,PARAM_LOB);
$statement->execute();

Categories