I'm trying to insert calculate values to Database.a and b from text field.this is my code.but it doesn't work.please help me
<?php
require('dbconnection.php');
$a=$_POST['a'];
$b=$_POST['b'];
class cal{
public function insert($a,$b){
if((($a)&&($b))!="")
{
$c=$a*$b;
$sql = "INSERT INTO cropplant (sbetweenQ ,sbetweenC ,sbetweenTC ) VALUES ('$a', '$b', '$c')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("DB Update error ! please Re-enter your details.");</script>';
}else
{
echo '<script type="text/javascript">alert("New value Added Successfuly.");</script>';
}
}else{
echo"please enter all";
}}}
?>
Your function basically does nothing. You fetch two post variables, and define a class. What you need to do is call the function in the class to process the two variables.
Related
I have a form with 2 drop down lists. Both with values from database tables.
When a visitor submits then the next things will occure:
A select query will compare the choices (id's)/POST values with the values (id's) in the database tables. The query will be fetched in the while loop. In the while loop is a if-else which controls if the values are equal to each other. When they are then run else.
In else there is the insert query which saves the values (id's) in a new database table.
I use prepared statements for both the select and the insert queries.
After fetching the select query I close it in else ($selControl->close();) and start the 2nd query (insert).
When I run the website with a submit then I get the error "Couldn't fetch mysqli_stmt" for the select query. But still it works and inserts into the DB table.
When I write $selControl->close(); (inclusive/exclusive $insKeuze->close(); from insert) after } of the 3rd else or after } after while then I get the error that the 1st query must be closed before a new prepare statement (that's logic).
Without a close statement gives also a "close-before-prepare" error.
I updated my code.
I added bind_param. It sends the data to the database, but gives the error.
What do I need to do to stop the error?
If someone can help me, thanks in advance!
The code: insert.php
<?php
// Include database configuration file
include ("dbConfig.php");
$kLand = $_POST["landen"];
$kGerecht = $_POST["gerechten"];
// If submit and landKeuze is not empty and gerechtKeuze is not empty
// --> control and validate the values and send to database.
if (isset($_POST["submit"]) && !empty($kLand) && !empty($kGerecht))
{
// If query is prepared then execute the query.
// Query to select data from table landen with inner join table gerechten.
if ($selControl = $mysqli->prepare("SELECT landen.land_id, gerechten.gerecht_id FROM landen INNER JOIN gerechten ON landen.land_id = gerechten.land_id WHERE landen.land_id = ? AND gerechten.gerecht_id = ?"))
{
$selControl->bind_param("ii", $kLand, $kGerecht);
if (!$selControl->execute())
{
echo "Failed to execute the query controle: " . $mysqli->error;
}
else
{
$selControl->bind_result($lLand_id, $gGerecht_id);
while ($selControl->fetch()) // <-- Coudn't fetch
{
// If selected land (land_id) is not the same as land_id in table landen
// or selected gerecht (gerecht_id) is not the same as gerecht_id in table gerechten --> send echo.
if ($kLand != $lLand_id || $kGerecht != $gGerecht_id)
{
// Message when the combination is not correct
echo "<script>alert('Deze combinatie bestaat niet. Doe een nieuwe poging!');</script>";
}
// Else insert the selected values in table landGerecht.
else
{
$selControl->close();
// If query is prepared --> bind the columns and execute the query.
// Insert statement with placeholders for the values to database table landGerecht
if ($insKeuze = $mysqli->prepare("INSERT INTO lab_stage_danush . landGerecht (land_id, gerecht_id) VALUES ( ?, ?)"))
{
// Bind land_id and gerecht_id as integers with $landKeuze and $gerechtKeuze.
$insKeuze->bind_param('ii', $kLand, $kGerecht);
// If statement is not executed then give an error message.
if (!$insKeuze->execute())
{
echo "Failed to execute the query keuze: " . $mysqli->error;
}
$insKeuze->close();
}
// Else give an error message.
else
{
echo "Something went wrong in the query keuze: " . $mysqli->error;
}
}
}
}
}
else
{
print_r($mysqli->error);
}
// After sent to database go back to keuze.php.
echo "<script>location.replace('keuze.php');</script>";
}
?>
This structure gives the same error:
<?php
while ($selControl->fetch())
{
echo "<script>alert('". $kLand . $kGerecht . $lLand_id . $gGerecht_id . "')</script>";
// If selected land (land_id) is not the same as land_id in table landen
// or selected gerecht (gerecht_id) is not the same as gerecht_id in table gerechten --> send echo.
if ($kLand == $lLand_id && $kGerecht == $gGerecht_id)
{
$selControl->close();
// If query is prepared --> bind the columns and execute the query.
// Insert statement with placeholders for the values to database table landGerecht
if ($insKeuze = $mysqli->prepare("INSERT INTO lab_stage_danush . landGerecht (land_id, gerecht_id) VALUES ( ?, ?)"))
{
// Bind land_id and gerecht_id as integers with $landKeuze and $gerechtKeuze.
$insKeuze->bind_param('ii', $kLand, $kGerecht);
// If statement is not executed then give an error message.
if (!$insKeuze->execute())
{
echo "Failed to execute the query keuze: " . $mysqli->error;
}
$insKeuze->close();
} else // Else give an error message.
{
echo "Something went wrong in the insert query connection: " . $mysqli->error;
}
} else // Else insert the selected values in table landGerecht.
{
// Message when the combination is not correct
echo "<script>alert('Deze combinatie bestaat niet. Doe een nieuwe poging!');</script>";
}
}
?>
So as you said in the comments, you believe you're getting a conflict between your mysql connections. I've gone ahead and created a class that should resolve this.
landen.php
class landen{
//define our connection variable, this is set in __construct
private $mysqli;
//this function is called when you create the class. $l = new landen($mysqlconn)
public function __construct($mysqli){
$this->mysqli = $mysqli;
}
//setter for kLand
private $kLand = 0;
public function setKland($k){
$this->kLand = $k;
}
//setter for kGerecht
private $kGerecht = 0;
public function setKGerecht($k){
$this->kGerecht = $k;
}
//run is our main function here.
//if there was a return from select, it runs the insert.
//will return true if select + insert BOTH pass.
public function run(){
if($this->select()){
return $this->insert();
}
return false;
}
private function select(){
$q = "SELECT landen.land_id, gerechten.gerecht_id FROM landen INNER JOIN gerechten ON landen.land_id = gerechten.land_id WHERE landen.land_id = ? AND gerechten.gerecht_id = ?";
if($stmt = $this->mysqli->prepare($q)){
$stmt->bind_param("ii",$this->kLand,$this->kGerecht);
if($stmt->execute()){
while ($stmt->fetch()){
/*
In your original code, you had a check to see if
your post variable was the same as your returned query variables.
This was not required as you are selecting from your database with those.
They will **always** equal the post variables.
Line I'm disputing: if ($kLand != $lLand_id || $kGerecht != $gGerecht_id)
*/
return true;
}
}else{
print_r("Error in select execute: {$this->mysqli->error}");
}
}else{
print_r("Error in select prepare: {$this->mysqli->error}");
}
return false;
}
private function insert(){
$q = "INSERT INTO lab_stage_danush . landGerecht (land_id, gerecht_id) VALUES ( ?, ?)";
if($stmt = $this->mysqli->prepare($q)){
$stmt->bind_param("ii",$this->kLand,$this->kGerecht);
if($stmt->execute){
return true;
}else{
print_r("Error in insert execute {$this->myqsli->error}");
}
}else{
print_r("Error in insert prepare {$this->mysqli->error}");
}
return false;
}
}
And here's an example on how you run this;
insert.php
<?php
require_once("dbConfig.php");
if(isset($_POST["submit"]) && !empty($_POST['landen']) && !empty($_POST['gerechten'])){
//Call the class code when we need it
require_once("landen.php");
//create the class when we need it.
$landen = new landen($mysqli);
//set our variables
$landen->setKland($_POST['landen']);
$landen->setKGerecht($_POST['gerechten']);
//landen run returns True if the select + insert statment passed.
//It will return false if they fail.
//if they fail, the page will not change and the errors will be outputted.
//Or it's failing because nothing has been returned by the select function.
if($landen->run()){
//send out header to go to Keuze page,
//you had a javascript location function here.
header("Location: keuze.php");
die();
}else{
//by default, let's say our queries are running fine and the only reason the select failed is because
//the database couldn't find anything.
echo "Nothing found with {$_POST['landen']} and {$_POST['gerechten']}. Please try again!";
}
}
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
I'm new to php.I'm trying to build a signup webpage in which if email entered doesn't exist it should insert the values entered.The code works fine and it returns successful when a new mail is entered.But the problem is when I check my database the new values are not inserted.Is there any mistake in my code?
Thanks in advance.
<?php
session_start();
if(isset($_POST['signup'])){
include_once("db.php");
$email=strip_tags($_POST['emailid']);
$username=strip_tags($_POST['username']);
$password=strip_tags($_POST['password']);
if($email==NULL || $username== NULL || $password==NULL){
print "Missing one of the fields";
}
else{
$email=stripslashes($email);
$username=stripslashes($username);
$password=stripslashes($password);
$email=mysqli_real_escape_string($db,$email);
$username=mysqli_real_escape_string($db,$username);
$password=mysqli_real_escape_string($db,$password);
$query = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($db,$query);
if($result && mysqli_num_rows($result) > 0 )
{
echo "Account already exists.Please login";
}
else{
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
if($sql)
{
echo "Account created successfully.";
}
else
{
echo "Error";
}
}
}
}
?>
You are not executing the insert query, it should look like:
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
$sql= mysqli_query($db,$sql); ///You are missing this
Change from:
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
if($sql)
{
echo "Account created successfully.";
}
To:
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
if(mysqli_query($db,$sql))
{
echo "Account created successfully.";
}
You need to execute the 2nd query ($sql)
$sql="INSERT INTO user (email,username,password) VALUES
('$email','$username','$password')";
if(mysqli_query($db,$sql))
{
echo "Account created successfully.";
}
Remove the null INSERT value it's not needed and should be auto generated if auto-incremental index.
execute the $sql statement a a MySQLi_query and then use the result of that in the IF statement.
Bonus: Use mysqli_error($db) to feed you back errors you will encounter, such as:
mysqli_query($db,$sql) or die("error: ".mysqli_error($db));
I have a form, on isset function data is inserted in db also it returns a variable named id from db. i want to post this variable to next page.
here is code;
if (isset($_POST['preview'])){
echo $user = $_SESSION['ue'];
echo $title=$_POST['title'];
echo $dis=$_POST['dis'];
echo $a=$_POST['a'];
echo $b=$_POST['b'];
echo $c=$_POST['c'];
echo $d=$_POST['d'];
echo $timespan=$_POST['timespan'];
$sql="INSERT INTO survey (user, title, description, opta, optb,optc,optd,time) VALUES ('$user','$title', '$dis', '$a' , '$b', '$c', '$d','timespan')";
if (mysqli_query($con,$sql))
{
echo "Success";
}
else
{
echo "Error: " . mysql_error();
}
$id = mysqli_insert_id($con); //variable to send to next page
mysqli_close($con);
}
?>
Thanks in advance :)
You can send it not next page using GET attribute in url as:
header("Location: http://mydomain.com/myOtherPage.php?id=".$id);
In myOtherPage you can use:
if(isset($_GET['id']))
{
$idFromPreviousPage=$_GET['id'];
}
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.