can't insert into database (webservice) - php

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;

Related

Issue trying to insert data into a MySQL table with 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..

What is the error in querying this? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
What's wrong on that code? -- It's keep refusing to create account.
$query = "
INSERT INTO `accounts`(`username`, `dispname`, `email`, `password`, `type`, `blocked`, `points`)
VALUES ($disname,$username,$email,$password,1,false,0)";
$result = mysql_query($query);
if($result){
$Registered = "You have registered successfully.";
} else {
$ERROREMAIL = "There Were an Error Registering your email, please contact our support.";
}
I am totally confused.
By the way this is the structure of the database, hopefully someone helps.
CREATE TABLE `accounts` (
`id` int(11) NOT NULL,
`username` varchar(255) DEFAULT NULL,
`dispname` varchar(255) NOT NULL DEFAULT 'someone',
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`type` int(10) NOT NULL,
`blocked` tinyint(1) NOT NULL DEFAULT '0',
`points` int(10) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
ALTER TABLE `accounts`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`);
ALTER TABLE `accounts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
Try this Query:
$query = "INSERT INTO `accounts`
(`username`, `dispname`, `email`, `password`, `type`, `blocked`, `points`)
VALUES ('$disname','$username','$email','$password',1,0,0)";
What change?
Adding single quote on string variables.
Also changed the value of blocked column as 0.
OP's comment:
"$connection = mysqli_connect($DBHOST, $DBUSER, $DBPASS, $DBNAME); also mysqli_query($connection, $query); – Ahmed Alaa 1 hour ago"
2 things wrong here. You're connecting with mysqli_ then querying with mysql_.
$result = mysql_query($query);
which should read as
$result = mysqli_query($connection, $query);
Those different APIs do NOT intermix. You must use the same one from connecting to querying.
Can I mix MySQL APIs in PHP?
Then, missing quotes around your variables (for strings) in values.
VALUES ($disname,$username,$email,$password,1,false,0)";
which should read as:
('$disname','$username','$email','$password',1,false,0)
But that leaves you open to SQL injection.
Use mysqli_* with prepared statements, or PDO with prepared statements.
Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code during testing.
This does not help you during testing in order to get the real error(s):
else {
$ERROREMAIL = "There Were an Error Registering your email, please contact our support.";
}
This will:
else {
echo "Error: " . mysqli_error($connection);
}
You can set it back to your original method once there are no more errors.
You need to pass strings as strings not as integers
Try this:
$query = "
INSERT INTO `accounts`(`username`, `dispname`, `email`, `password`, `type`, `blocked`, `points`)
VALUES ('$disname','$username','$email','$password',1,false,0)";
Thanks for you all.
Solution is as it is.
Updating your php version to PHp 7_0_0.
Updating phpmyadmin to 4_5_2.
Updating MySql to 5_6_27.
Update the usage of old mysql -> PDO.

Mysql does not store blob column data

I have strange problem that I am unable to figure out, any help would be appreciated!.
The problem is I am trying to store an object into mysql database, when I execute the insertion command I run successfully, but when I check the table, all columns have the new inserted data expect the column with Blob datatype.
here is the table
CREATE TABLE `uc_opportunities` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`org_id` int(11) DEFAULT NULL,
`dateTime` int(11) NOT NULL,
`subject` varchar(200) NOT NULL,
`text` varchar(2000) DEFAULT NULL,
`zipcode` varchar(10) NOT NULL,
`location` varchar(100) DEFAULT NULL,
`schedule` blob NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8;
and here is the insertion function:
public function addOpportunity($org_id)
{
global $mysqli,$emailActivation,$websiteUrl,$db_table_prefix; //
echo "inside add opportunity<br>";
var_dump($this->schedule);
$stmt = $mysqli->prepare("INSERT INTO ".$db_table_prefix."opportunities (
org_id,
dateTime,
subject,
text,
zipcode,
schedule
)
VALUES (
?,
?,
?,
?,
?,
?
)");
$schedule_serialized = serialize($this->schedule);
$stmt->bind_param("iissib", $org_id, $this->dateTime, $this->subject,$this->postText, $this->zipcode, $schedule_serialized );
$result = $stmt->execute();
echo "execution result ".$result."<br>";
$inserted_id = $mysqli->insert_id;
$stmt->close();
$this->post_id = $inserted_id;
}
All columns except schedule are inserted, I check if the insertion function receive the schedule correctly using var_dump($this->schedule) and it is correct. What do you think might be the problem?
Thank you
Please check out the mysqli documentation in reference to saving blob data and mysql config for max_allowed_packet. It's possible this could be your issue since I don't know how big your serialized data is:
php.net mysqli
first of all,change your data if it is image,audio,document etc into binary and schedule column to longBlob then run your insert command.Some times due to larger binary data insert doesn`t work.So give a try

Custom PHP script PDO is throwing exception 23000,1062 duplicate entry

I am working on a PHP script where I am using PDO to insert data in mySQL. I am getting an error "23000",1062,"Duplicate entry 'email#email.com-username' for key 'email' but its inserting the data in database.
So here is my PHP codes:
if(isset($_POST['email'])){
$this->db = new connect();
$this->db = $this->db->dbConnect();
$this->encryption = new Encryption();
isset($_POST['timezone']) AND $_POST['timezone'] != 'null' ? date_default_timezone_set($_POST['timezone']): date_default_timezone_set('America/Chicago');
$this->email = $_POST['email'];
$this->username = $_POST['username'];
$this->password = $this->encryption->encode($_POST['password']);
$this->dTime = date("Y-m-d H:i:s");;
$this->sessionKey = $_POST['key'];
$this->country = $_POST['country'];
$this->region = $_POST['uregion'];
$this->browser = $_POST['browser'];
$this->ip = $_POST['accessFrom'];
$regMessage = array('error'=>false);
try{
$query = "INSERT INTO `users` (
id, email, uname, password, regtime, sessionkey, country, region, browser, ip
) VALUES (
(SELECT MAX(id) + 1 FROM `users` AS `maxId`), :email, :uname, :password, :regtime, :sessionkey, :country, :region, :browser, :ip
)";
$register = $this->db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
if($this->sessionKey === $_SESSION['token']){
$register->bindParam(':uname', $this->username);
$register->bindParam(':email', $this->email);
$register->bindParam(':password', $this->password);
$register->bindParam(':regtime', $this->dTime);
$register->bindParam(':sessionkey', $this->sessionKey);
$register->bindParam(':country', $this->country);
$register->bindParam(':region', $this->region);
$register->bindParam(':browser', $this->browser);
$register->bindParam(':ip', $this->ip);
$register->execute();
if($register->rowCount() > 0){
$regMessage = array('error'=>false);
}else{
$regMessage = array('error'=>true);
}
}else{
throw new PDOException ('Error');
}
}
catch(PDOException $e){
//this is where I am getting error so I am echoing pdo exception error
$regMessage = array('error'=>$e);
}
header('Content-Type: application/json');
echo json_encode($regMessage);
}else{
header('Location: /');
}
At the error, it is showing me duplicate entry of emailid + username for key email which looks like email#email.com-username
But in data base, I am getting email id only in email column and username only in username column.
So can any one tell me whats wrong in my codes?
My users table structure is
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(250) CHARACTER SET utf8 NOT NULL,
`uname` varchar(20) CHARACTER SET utf8 NOT NULL,
`password` varchar(100) CHARACTER SET utf8 NOT NULL,
`regtime` datetime NOT NULL,
`sessionkey` varchar(10) CHARACTER SET utf8 NOT NULL,
`country` varchar(25) CHARACTER SET utf8 NOT NULL,
`region` varchar(25) CHARACTER SET utf8 NOT NULL,
`browser` varchar(25) CHARACTER SET utf8 NOT NULL,
`ip` varchar(16) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`,`uname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
So can anyone tell me where and what is wrong?
Thank you for helping me.
The phrasing in the error message: 'email#email.com-username' for key 'email' directly corresponds to your unique key UNIQUE KEY 'email' ('email','uname'). With that line, you are creating a compound key, which you can think of as an invisible column in the index that is comprised of email-uname. There will not be a column added to your table with this format, and you are seeing the expected behavior that email and uname are treated separately in the table and together for the key.
If you want to test over and over again with the same email and username combo, you'll need to delete that row every time. Without doing this, the error you are seeing is exactly what I would expect to see if you are POST-ing the same data over and over again.
I want to also mention that you have (appropriately) specified that your id column is AUTO_INCREMENT, but then you are calculating the value manually. I would like to discourage you from doing this, and instead use NULL as the insert value. MySQL will use the correct key value in this column, and you will avoid the potential for key collision if you ever had two of these things executing at the same exact moment.
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(250) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`uname` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varchar(100) CHARACTER SET utf8 NOT NULL,
`regtime` datetime NOT NULL,
`sessionkey` varchar(10) CHARACTER SET utf8 NOT NULL,
`country` varchar(25) CHARACTER SET utf8 NOT NULL,
`region` varchar(25) CHARACTER SET utf8 NOT NULL,
`browser` varchar(25) CHARACTER SET utf8 NOT NULL,
`ip` varchar(16) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
this is the solution.

Netbeans Xdebug: mysqli_affected_rows returns "-1" when it should be "1"

I'm puzzled why the following code successfully adds a new row to my database table while mysqli_affected_rows($dbc) returns "-1", thus an error, in signup.php:
dbc.inc.php :
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'v');
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Error connecting to MySQL server.');
mysqli_set_charset($dbc, 'utf8');
signup.php :
require('dbc.inc.php');
//code to set variables for the following SQL statement
$q = "INSERT INTO users (username, email, pass, first_name, last_name, sex, birth_day, birth_month, birth_year, phone, street, street_nr, city, zip_code, country, user_img) VALUES ('$u', '$e', '$p', '$fn', '$ln', '$sex', '$bd', '$bm', '$by', '$pn', '$st', '$sn', '$cit', '$pc', '$ct', '$user_img')";
$r = mysqli_query($dbc, $q) or die(msg(0, "Error connecting to the database"));
if (mysqli_affected_rows($dbc) === 1) { //Returns 'false' despite one row having been added...
echo "Success";
}
else {
echo "Error"; //...resulting in "Error" being echoed
}
For testing purposes: SQL to create table "users":
CREATE TABLE IF NOT EXISTS `v`.`users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`type` ENUM('member','admin') NOT NULL DEFAULT 'member',
`username` VARCHAR(45) NOT NULL,
`email` VARCHAR(80) NOT NULL,
`pass` VARCHAR(255) NOT NULL,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`sex` CHAR(1) NOT NULL,
`birth_day` INT NOT NULL,
`birth_month` INT NULL,
`birth_year` INT NULL,
`phone` VARCHAR(20) NULL,
`street` VARCHAR(60) NOT NULL,
`street_nr` VARCHAR(9) NOT NULL,
`city` VARCHAR(45) NOT NULL,
`zip_code` VARCHAR(45) NOT NULL,
`country` VARCHAR(45) NOT NULL,
`user_img` VARCHAR(65) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `username_UNIQUE` (`username` ASC),
UNIQUE INDEX `email_UNIQUE` (`email` ASC),
INDEX `login` (`email` ASC, `pass` ASC))
ENGINE = InnoDB
AUTO_INCREMENT = 4
DEFAULT CHARACTER SET = utf8;
I'd be very grateful for your hints!
EDIT:
I have meanwhile been able to isolate the problem a little further: the code works fine run directly in a web browser, it's just in Netbeans/Xdebug that mysqli_affected_rows($dbc) in the according line first correctly returns "1", but after stepping into the following line (F7) suddenly changes to "-1" and thus wrongly jumps to the "else"-branch returning an error although the data is correctly written to the database. Apparently I'm not the only one having this problem.
These are my Xdebug Settings in php.ini, but I think they are correct.
zend_extension = "C:\xampp\php\ext\php_xdebug.dll"
;xdebug.profiler_append = 0
xdebug.profiler_enable = 1
;xdebug.profiler_enable_trigger = 0
;xdebug.profiler_output_dir = "C:\xampp\tmp"
;xdebug.profiler_output_name = "cachegrind.out.%t-%s"
xdebug.remote_enable = 1
xdebug.remote_handler = "dbgp"
xdebug.remote_host = "localhost"
xdebug.remote_port = 9000
;xdebug.trace_output_dir = "C:\xampp\tmp"
Any clues anybody?
I have tested your code and it echos Success when new record inserted to database, please recheck your database to ensure data insertion
mysqli_affected_rows: return value
- An integer > 0 indicates the number of rows affected.
- 0 indicates that no records where affected &
-1 indicates that the query returned an error(that may be you case)

Categories