So Ive been debugging this for a couple of hours and can't seem to work it out. Ive got a form that takes info into a session then from sessions it goes into a class.
form->session->class->database
Inside the class theres a function that looks like this:
function lagre($kunde)
{
$navn = $kunde->GetNavn();
$telefon = $kunde->GetTelefon();
$epost = $kunde->GetEpost();
$antall = $kunde->GetAntall();
$db = mysqli_connect("localhost","root","","Billett");
if($db->connect_error)
{
die("Couldn't connect");
}
else {
echo "Connected";
}
$sql = "INSERT INTO `Billett`.`Billett` (`BillettID`, `Navn`, `Telefon`, `Epost`, `Antall`) VALUES (NULL, '$navn', '$telefon', '$epost', '$antall')";
$resultat = mysqli_query($db,$sql);
if(!$resultat)
{
echo "<br> Values not inserted";
}
else {
echo "<br> Values inserted";
}
}
The problem is that the values doesn't insert into the database. I cant work out why. Any ideas?
You try to write in different way
$sql = "INSERT INTO `Billett`.`Billett` (`BillettID`, `Navn`, `Telefon`, `Epost`, `Antall`) VALUES (NULL, '".$navn."', '".$telefon."', '".$epost."', '".$antall."')";
Are you using Autocommit? If not then you need to commit your data to the DB, otherwise your INSERT doesn't stick:
/* commit transaction */
if (!$mysqli->commit()) {
print("Transaction commit failed\n");
exit();
}
Example from PHP documentation
Related
I'm making a simple CURD operation using PHP and MYSQL. However I'm not able to insert/add data in the created table.
I think it might be a syntax error itself, but I can't figure out which one. The rest of the code works fine.
operation.php:
require_once("../CRUD/php/db.php");
$conn = createDB();
if(isset($_POST['create']))
{
createData();
}
function createData()
{
$name = textboxValue("name_type");
$age = textboxValue("age_type");
$gender = textboxValue("gender_type");
$email = textboxValue("email_type");
$contact = textboxValue("contact_type");
$dept = textboxValue("dept_type");
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES('$name', '$age', '$gender', $email', '$contact', '$dept');";
if(mysqli_query($GLOBALS['conn'],$sql))
{
echo "Data added";
}
else
{
echo "Error adding data";
}
}
function textboxValue($value)
{
$textbox = mysqli_real_escape_string($GLOBALS['conn'], trim($_POST[$value]));
if(empty($textbox))
{
return false;
}
else
{
return $textbox;
}
}
"Error adding data" gets echoed. I can share the html code as well if needed.
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES(\"$name\", \"$age\", \"$gender\", \"$email\", \"$contact\", \"$dept\");";
and so? By the way one quote you forgot near $email
I want to create a simple piece of code that will put data into the database form a PHP script, everything works fine except putting the data into the database! (I am running a server with PHP7)
The output of the affected rows shows -1 (strange), I double checked my code, compared it with others, tried searching for a common issue on the internet, even tried on a local server with no avail.
You can see it here:
https://leer.bosvision.nl/register.php
My code:
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = 'INSERT INTO users_two (ID, username, password) VALUES (1, gfd, gfd)';
if(mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
To quote the documentation:
-1 indicates that the query returned an error.
And your insert statement indeed errors out, since you don't have a gfd column. If you meant to use that as a value, it should be surrounded by single quotes:
$query = "INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')";
# Here -------------------------------------------------------------^---^--^---^
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = "INSERT INTO users_two (username, password) VALUES ('gfd', 'gfd')";
if($result= mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
One assumes ID is auto increment, so that doesn't need to be in there, or is it not and the issue you are encountering is that its a duplicate entry for key. Also you need to wrap your var data in ' '
I would guess that this is an SQL issue. Can you run your query directly on your database? That would give you the error.
Read this page for more info: PHP insert statement
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Normally you shouldn't be inserting an ID yourself because it should be auto increment.
try adding quotes to the string values, as in:
"INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')"
<?php
$db = new mysqli("localhost", "HIDDEN", "HIDDEN", "HIDDEN");
if ($db->connect_error) {
die("Failed to connect.");
}
if (isset($_POST["title"]) && isset($_POST["description"]) && isset($_POST["url"])) {
$title = $db->real_escape_string($_POST["title"]);
$description = $db->real_escape_string($_POST["description"]);
$url = $db->real_escape_string($_POST["url"]);
$sql = "INSERT INTO video (name, description, submission_date)
VALUES ('{$title}', '{$description}', CURDATE());
INSERT INTO video_source (video_id, url)
VALUES (LAST_INSERT_ID(), '{$url}');";
if ($db->query($sql) === TRUE) {
echo "Successfully added.";
} else {
echo "Query failed.<br><br>Data: {$title} {$description} {$url}";
}
} else {
echo "Data not set.";
}
$db->close();?>
Outputs "Query failed." with the data I entered. Replacing variables such as title with constants still has the same problem. I tried the query in PHPMyAdmin and it worked fine (with constants).
It seems to be unhappy with setting the value of video_id.
Anytime you're running multiple queries with MySQLi you should use multi_query():
$db->multi_query($sql)
In addition, LAST_INSERT_ID() in your second query is not returning any sort of value. If you're looking for the last inserted value of the 1st query you have to return that prior to running the second query.
I created a form using php, mysql and xampp server. The problem is that whatever I write in this form it shows that the "message failed to send" and even when I check my db using http://localhost/phpmyadmin/ the message is not there. Here is the code.
P.S I followed a video tutorial and it is exactly the same that made me totally lost. Please help.
The Connection code is:
<?php
$db_host = 'localhost';
$db_user= 'root';
$db_pass= 'the password';
$db_name= 'chat';
if ($connection= mysql_connect($db_host, $db_user, $db_pass)) {
echo "Connected to Database Server...<br />";
if ($database= mysql_select_db($db_name, $connection)) {
echo "Database has been selected... <br />";
} else {
echo "Database was not found. <br />";
}
} else {
echo "Unable to connect to MYSQL server.<br />";
}
?>
And the function code is:
<?php
function get_msg() {
$query = "SELECT 'Sender', 'Message' FROM 'chat' . 'chat'";
$run = mysql_query($query);
$messages= array();
while($message = mysql_fetch_assoc($run)) {
$messages[]= array ('sender' =>$message['Sender'],
'message'=>$message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)){
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";
if($run = mysql_query($query)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
I have found the problem in your SQL query:
$query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";
You have to specify the fields there, the SQL query is invalid. Also you have used the wrong escape characters. This works:
$query = "INSERT INTO `chat`.`chat` (`ID`, `sender`, `message`) VALUES (null, '{$sender}', '$message')";
You do not have to specify a null value if you use AUTO_INCREMENT:
$query = "INSERT INTO `chat`.`chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";
And please use MySQLi instead of MySQL because it is deprecated. Furthermore, the database should not be specified twice, simple use:
$query = "INSERT INTO `chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";
$query = "INSERT INTO `chat`.`chat` VALUES (null, '{$sender}', '$message')";
Note the ` and it's not '
I am a novice in PHP and MySQL so I tend to always explicitly exit or die on MySQL on errors.
<?php
$db = new mysqli('host', 'username', 'password', 'db');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
// no reason to continue, no db connection
}
$statement="SELECT * from `bufferlines` WHERE `beloeb` >'-400' AND `tekst` LIKE 'Dankort-nota SuperB%'";
if(!$res=$db->query($statement)){
printf("Error: %s\n", $db->error); //show MySQL error
echo "<br />".$statement; // show the statement that caused that error
exit("Error 4");//no reason to continue, show where in code
}
?>
This way I get it thrown in my face and cannot get any further until I have pinned down and corrected the error.
The number in exit("Error 4") is only to find the place in the code where it went wrong and thus is unique.
I know this is counter productive when you know your stuff, but for me it's an invaluable learning tool together with php.net dev.mysql.com and stackoverflow.com
i have code for save 3 textbox in one field in databse
no problem when i am enter 3 textbox , but when i fill 1 textbox and press ok
save another textbox in database as blank
i want just take the textbox is fulled and ignore the textbox empty
this is my code
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result=mysql_query($sql);
$result2=mysql_query($sql2);
$result3=mysql_query($sql3);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
Execute your sql query only the variable value not equal to empty.
try this,
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if ($expert_name != "") {
$sql = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result = mysql_query($sql);
}
if ($expert_name2 != "") {
$sql2 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2 = mysql_query($sql2);
}
if ($expert_name != "") {
$sql3 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 = mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if ($result || $result2 || $result3) {
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
You should also check $result2 and $result3. I added that in this answer
try this
if ( !empty($_POST['expert_name']) ){
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if ( !empty($_POST['expert_name2']) ){
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if ( !empty($_POST['expert_name3']) ){
$sql3 ="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 =mysql_query($sql3 );
}
Then you might want to check if the variable is empty().
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if(!empty($expert_name)) {
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if(!empty($expert_name2)) {
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if(!empty($expert_name3)) {
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3=mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
Also note: You only check if $result is okay. If you only fill textbox 2 and leave 1 empty, the value of 2 it will get inserted but an error is shown.
I'd say your code need general review, but as it is for now you will have to do something like this each query:
if (!empty($expert_name2){
$result2=mysql_query($sql2)
}
But you should try to loop your queries in foreach rather than manually write every on query. And by the way:
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
This code only return succes when 1st wuery success because you use $result which is set in 1st query only
The ID is probably NOT NULL AUTO_INCREMENT, so that won't accept NULL as value.
try sending blank value, such as:
$sql="INSERT INTO experts(id,expert_name) VALUES ('', '$expert_name')";
Also, build bulk insert, rather than multiple.
I will explain why, when you insert single insert into the database, the values being inserted, then, the DB engine flushes indexes (they written to disk), unless you have set delay_key_write=ALL in you my.cnf. Index flushing directly affects your db performance.
Please, check the reworked code out. The code adjusted for bulk insert, sql string escaping for security purposes and additional verification for post keys existence.
<?php
include("connect.php");
// this is for arabic language.
mysql_query("SET NAMES utf8");
$values = array();
$skipInsert = true;
$fields = array('expert_name', 'expert_name2', 'expert_name3');
$insert = "INSERT INTO experts(id,expert_name) VALUES ";
// Loop through predefined fields, and prepare values.
foreach($fields AS $field) {
if(isset($_POST[$field]) && !empty($_POST[$field])) {
$values[] = "('', '".mysql_real_escape_string(trim($_POST[$field]))."')";
}
}
if(0 < sizeof($values)) {
$skipInsert = false;
$values = implode(',', $values);
$insert .= $values;
}
if(false === $skipInsert) {
mysql_query($insert);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful","<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR","<br>",mysql_error(),"<a href='expert_add.php'><br>Please try again </a>";
}
HTH,
VR
if(!empty($textbox1_value)) {
//DO SQL
}
You can repeat this for multiple boxes however you wish, the empty operator checks if its empty, so if its not empty the "//DO SQL" area will get run.