I have a page which allows a user to create an entry and insert it into the database via submitting a form through PHP.
I have had the page working in the past, and it worked perfectly, but now for some reason it has stopped working. Basically, I submit the form, and there are no error messages, but my entry does not appear in the database.
Here is my PHP:
<?php // add_entry.php
session_start();
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");
if (isset($_POST['group'])){
$lab = $_SESSION['labname'];
$author = $_SESSION['username'];
$name = $_POST['entryName'];
$group = $_POST['group'];
$protocol = $_POST['protocol'];
$permission = $_POST['permission'];
$array = $_POST['protocolValues'];
// $filearray = $_POST['fileArray']; Don't forget to add '$filearray', to your query after ARRAY.
$project = $_POST['project'];
$query = "INSERT INTO data (protocol, name, lab, author, uniquearray, usergroup, project, permissionflag) VALUES ('$protocol', '$name', '$lab', '$author', '$array', '$group', 'project', '$permission')";
mysqli_query($con, $query);
mysqli_close($con);
}else{
echo "FAILURE. GROUP WAS NOT SET.";
}
?>
Any ideas as to why this may be happening?
Thanks in advance!
In addition to the accepted answer which I applaud, this 'project' in your VALUES()
is missing the $ sign - therefore, it's not being passed as a variable but as a simple string.
so change it to '$project'
otherwise, the value entered in DB will be project and not the intended POST value from your form.
You're also not checking for errors, which is crucial during the development stages of a project.
Add error reporting to the top of your file(s)
error_reporting(E_ALL);
ini_set('display_errors', 1);
which will signal any errors found in your code.
try to add
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
after $con=mysqli_connect(...);
and replace this
mysqli_query($con, $query);
with this
if (!mysqli_query($con, $query)) {
printf("Errormessage: %s\n", mysqli_error($con));
}
you will be able to debug the problem (if related to the query)
Related
Once again I come back to all of you with another question.
I have tried everything in my mind as well as most of the recommendations I have found on the web and here in Stackoverflow but nothing seems to fix this issue for me.
For some reason the sql command in my code is returning false even though it should not.
Here is my php file called (dbRKS-DBTest.php)
<?php
//Gets server connection credentials stored in serConCred.php
//require_once('/../prctrc/servConCred2.php');
require_once('C:\wamp64.2\www\servConCred2.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));
}
//VARIABLES & CONSTANTS
//Principal Investigator Information
$PI_Selected = '6';
//Regulatory Knowledge and Support Core Requests variables
$RKS_REQ_1_Develop = '1';
//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
$command = "SET AUTOCOMMIT = 0";
$result = mysqli_query($con, $command);
$command = "BEGIN";
$result = mysqli_query($con, $command);
//Delete this portion of code afyer testing is finished
//Core Requests saved to database
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop')";
//*************TEsts code for "SCOPE_IDENTITY()" -> insert_id() for mysql
$sqlInsertId = mysqli_insert_id($con); //This value is supposed to be 0 since no queries have been executed.
echo "<br>MYSQLi_INSERT_ID() value before query should be 0 and it is:= " . $sqlInsertId;
//Checks for errors in the db connection.
$result = mysqli_query($con, $sql); //Executes query.
if($result == false){ //Checks to see for errors in previews query ($sql)
//die ('<br>Error in query to Main Form: Research Proposal Grant Preparation: ' . mysqli_error($con));
echo "<br>Result for the sql run returned FALSE. Check for error in sql code execution.";
echo "<br>Error given by php is: " . mysqli_error($con);
$success = false; //Chances success to false is it encounted an error in order to rollback transaction to database
}
else{
//*************TEsts code for "SCOPE_IDENTITY()" -> insert_id() for mysql
$sqlInsertId = mysqli_insert_id($con); //Saves the last id entered. This would be for the main table
echo "<br>MYSQLi_INSERT_ID() value after Main form query= " . $sqlInsertId; //Displays id last stored. This is the main forms id
$MAIN_ID = mysqli_insert_id($con); //Sets last entered id in the MAIN Form db to variable
}
//Checks for errors or craches inside the code
// If found, execute rollback
if($success){
$command = "COMMIT";
$result = mysqli_query($con, $command);
echo "<br>Tables have been saved witn 0 errors.";
}
else{
$command = "ROLLBACK";
$result = mysqli_query($con, $command);
echo "<br>Error! Databases could not be saved. <br>
We apologize for any inconvenience this may cause. <br>
Please contact a system administrator at PRCTRC.";
}
$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);
?>
Here is my php frontend html code named (RPGPHomeQueryTest.php)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<form id="testQuery" name="testQuery" method="post" action="../dbRKS-DBTest.php" enctype = "multipart/form-data">
<input type="submit" value="Submit query"/>
</form>
</html>
And here is how my database looks (rpgp_form_table_3):
So, when I open my html code, All I will see is a button since its all the code there is there. Once you press the button, the form should submit and execute the php code called (dbRKS-DBTest.php). This should take the predetermine values I already declared and saved them to the database called (rpgp_form_table_3). This database is set to InnoDB format.
Now, the output I should be getting is a message saying "Tables have been saved witn 0 errors." but the problem is that the message I am getting is this one bolow:
I honestly don't know why. I am posting this message to find guidance to this issue. I am still learning by myself and its been very did-heartedly to not find a solution this fixing this.
As always, I thank you for your patient and guidance! Let me know what other details I can provide.
Here is the SQL code you run:
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop')";
You are inserting data into rpgp_form_table_3. From the screenshot, we can see that table has several (7) fields yet you are only inserting 2 fields. The question then is: do you need to specify a value for all fields?
The error you are getting states
Error given by php is: Field 'idCollaRecord_1' doesn't have a default value Error! Databases could not be saved.
It's clear that you have to insert the row by specifying a value for each column, not just the two columns you are interested in.
Try
$sql = "INSERT INTO rpgp_form_table_3 (idPl, RKS_REQ_1_Develop, idCollaRecord_1, idCollaRecord_2, idCollaRecord_3, idCollaRecord_4)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop',0,0,0,0)";
Try this insert code. If the PI_Selected is NUMERIC use the First one. If it is string use the second one
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop) VALUES (" .
$PI_Selected . ",'" . $RKS_REQ_1_Develop . "')";
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop) VALUES ('" .
$PI_Selected . "','" . $RKS_REQ_1_Develop . "')";
im adding data in databese with php and received "succesful" but when i look into the database the data which is i have just added doesnt show. Here my codes
<?php
require ('db.php');
#$name = $_POST['name'];
#$surname = $_POST['surname'];
#$number = $_POST['number'];
#$mail = $_POST['mail'];
#$note = $_POST['note'];
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if ($sql)
{
echo "Succesful";
}
else
{
echo "error";
}
?>
this is also my db.php codes ;
<?php
$con = mysqli_connect("localhost","root","","customers");
if (mysqli_connect_errno()) {
printf(" Connection error :( %s\n", mysqli_connect_error());
exit();
}
?>
i also have one more question. When i try to add data in databese with mysqli_query() function, it doesnt work. for example;
mysqli_query($con, "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES($name,$surname,$number,$email,$note)");
because of this , i had to use this code,its working now but i have no idea why mysqli_query() function is doesnt work
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if you help me it would be great, thank you.
Put single quote(') in values like this
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ('$name','$surname','$number','$mail','$note')";
You are checking just $sql variable which doesn't provide sql resul, it's just a query.
Try
$result = $con->query($sql);
if($result)
{
echo "Succesful";
}else{
echo "error";
}
More proper way:
$sql = "INSERT INTO `customersinfo`
(`name`,`surname`,`number`,`email`,`notes`) VALUES
('{$name}','{$surname}','{$number}','{$mail}','{$note}')";
$result=$con->query($sql);
if (!$result) {
// Query has failed
}
You checked $sql in if condition which is not right because $sql is always true so that u get the result successful but actually value is not getting inserted in database.
take the result in some variable and used that in if condition.
after that you will get what actual error in your code.
I looked at a dozen questions and nothing helps. Some give contradictory advice.
I have a simple INSERT INTO query with PHP mysqli. The query and the connection are both ok, and the query actually executes on an older version of xampp. But when I switched to a newer one - nothing! No errors, but, no new data, either.
<?php
$connection = mysqli_connect("localhost", "standard_user", "standard", "liquidity");
if (!$connection) {
die("Error: ".mysqli_connect_errno());
}
$table = "clan";
$username = "someusername";
$ime = "My name";
$query = "INSERT INTO ";
$query.=$table;
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
//$query = "INSERT INTO clan (username, ime) VALUES ('someusername', 'My name')";
mysqli_query($connection, $query);
if ($query) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again.");
}
mysqli_close($connection);
?>
This is the query it echoed when I tried it: INSERT INTO clan (username, ime) VALUES ('someusername','My name');
Since every time I reload it prints "Success: My name", I guess it somehow executes. But, no data is saved. I can't figure it out. Any help?
[SOLUTION] The clan table had a foreign key (username) to another table which had no entries, so there was nothing wrong with the query, but a silly overlook actually. Thanks to Deivison Francisco's answer, it was easy to determine the cause of the problem by simply reading an error.
Please use the return value of mysqli_query() to determine the result.
Also think about using prepared statements to mitigate SQL Injections.
$result = mysqli_query($connection, $query);
if ($result) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again. Error message: ".mysqli_error($connection));
}
Alter for:
$query = "INSERT INTO clan (username, ime) VALUES ('someusername', 'My name')";
$return = mysqli_query($connection, $query);
if ($return) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again.");
}
mysqli_close($connection);
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>
I am trying to insert values for longitude, latitude and descriptions of locations generated from google maps (the ID value is to be generated within PhpMyAdmin. When I run the following code I always get the "error" message. If I "echo $sql;" before //insert values into database then I get the intended output so I guess it must be a problem with transferring to the database.
I'm using phpMyAdmin from within MAMP so am not sure if that is causing any issues of whether I'm missing something obvious in the code? I'm fairly new to PHP so may have missed something obvious! Any help would be much appreciated.
<?php
$con=mysqli_connect("localhost", "root", "root", "googlemaps") or die("could not connent to db");
error_reporting(0);
for($i=0;$i<count($_POST['value']);$i=$i+3)
{
$sql .= "(NULL, '".$_POST['value'][$i]."', '".$_POST['value'][$i+1]."', '".$_POST['value'][$i+2]."'),";
}
//remove last comma
$sql = substr($sql,0,-1);
//insert values into database
$query = "INSERT INTO 'googlemaps'.'values' ('id', 'lat', 'lng', 'des') VALUES " .$sql;
$status = mysqli_query($con, $query);
if($status)
echo "inserted";
else
echo "error";
?>