data inserting with null values using PHP - php

here order_ID ,Bill may b null,a customer dont need to fill in the form ,,,here is the php code ,,,,,it is not working.....i dont know how to insert tuple with null values into table by using php.i cant find the errors.
create table Orders(
Order_ID number(10) primary key,
Cust_id number(5),
Order_date date,
Bill number(5,2),
CONSTRAINT fk_cust FOREIGN KEY (Cust_ID) REFERENCES Customer(Cust_ID)
);
CREATE SEQUENCE ord_seq;
CREATE OR REPLACE TRIGGER table_res
BEFORE INSERT ON Orders
FOR EACH ROW
BEGIN
SELECT ord_seq.NEXTVAL INTO :new.Order_ID FROM dual;
END;
/
<?php
$conn=oci_connect("system","123","localhost/orcl");
ob_start();
$current_file=$_SERVER['SCRIPT_NAME'];
$massage= "";
if(isset($_POST['Cust_id'])&&
isset($_POST['Order_date']))
{
$Cust_id= $_POST['Cust_id'];
$Order_date = $_POST['Order_date'];
if(!empty($Cust_id)&&!empty($Order_date))
{
$sql = "insert into Orders values('".NULL."','".$Cust_id."','".$Order_date."','".NULL."')";
$stid = oci_parse($conn,$sql);
$r = #oci_execute($stid);
if($r)
{
echo ' data is inserted...<br>';
}
else
{
echo 'data was not inserted...<br>';
}
}
else
{
$massage = "please fill up all the form correctly<br>";
}
}
?>
<html>
<head>
<title>Create FoodItem Table</title>
<style>
body
{
background:orange;
}
</style>
<head>
<body>
You dont need to fill Order_ID and Bill<br><br>
<?php echo $massage;?>
<hr color="green">
<form action="<?php echo $current_file;?>" method="POST">
Cust_id:<br> <input type="text" name ="Cust_id" ><br><br>
Order_date:<br> <input type="text" name="Order_date" ><br><br>
<input type ="submit" value="Submit Order"><br><br>
//Home
</form>
</body>
</html>

insert null values like this
$sql="insert into Orders values(NULL,'".$Cust_id."','".$Order_date."',NULL)";

Inserting a NULL value on your primary key is probably not what you want. Either insert a unique value for your key:
$sql = "insert into Orders values('". $someUniqueValueThatYouCreated . "','".$Cust_id."','".$Order_date."','".NULL."')";
--or--
alter your table structure with, say, an auto_increment:
Order_ID int(10) primary key auto_increment,
and then modify your insert:
$sql = "insert into Orders (Cust_id, Order_date, Bill) values('".$Cust_id."','".$Order_date."','".NULL."')";

Related

why can't i insert new values into my combined primary key?

i would like to insert values into my combined primary key. However, i only get the erorr message Duplicate entry '1-16' for key 'PRIMARY'
I am sure there is no connection problems as previous SELECT querys have worked, and everything else on the site is running. Below is my code for the segmet. I am very grateful for all help, but as i am a beginner i would really apreciate straightfoward and easy answers:) Thanks in advance!
<form method="post">
<select name="sport_id">
<?php
$sql= "SELECT * FROM sport";
$resultat= $kobling->query($sql);
while ($rad = $resultat->fetch_assoc()) {
$sport_id=$rad["sport_id"];
$sportName=$rad["name"];
echo "<option value='$sport_id'> $sportName </option>";
}
?>
</select>
<select name="person_id">
<?php
$sql= "SELECT person_id, fname, lname FROM person";
$resultat= $kobling->query($sql);
while ($rad= $resultat->fetch_assoc()) {
$person_id=$rad["person_id"];
$fname= $rad["fname"];
$lname =$rad["lname"];
$navn= $fname. " ". $lname;
echo "<option value='$person_id'> $navn </option>";
// code...
}
?>
</select>
Året du startet:
<input type="number" name="startyear" value="">
<input type="submit" name="leggtil3" value="Legg til">
</form>
<?php
if (isset($_POST["leggtil3"])) {
$person_id=$_POST["person_id"];
$sport_id = $_POST["sport_id"];
$startyear=$_POST["startyear"];
$sql= "INSERT INTO personsport (sport_id, person_id, startyear) values ('$sport_id', '$person_id', '$startyear')";
if ($kobling->query($sql)) {
echo "koblingen $sql ble gjennomført";
}
else {
echo "det var et problem med $sql ($kobling->error)";
}
}
?>
Your INSERT is attempting to assign a non-unique combination for PRIMARY fields. Auto Increment can mess up; ensure the next number in sequence is not taken.
Mysql Docs
Updating an existing AUTO_INCREMENT column value in an InnoDB table
does not reset the AUTO_INCREMENT sequence as it does for MyISAM and
NDB tables.
(It looks like your just entering the same person and sport twice. Those fields must be unique in combination due to your index.)
The primary keys 1 - 16 are already assigned in the database. Check the database to be sure your next value for auto increment does not hold any of these values.

Increment ID by getting the last record id from mysqli table

I am trying to get the last Employee ID from my Sqli table, increment the id retrieved from the table and insert the new value into the table along with the new record.
The code is not working as the table is not getting updated.
<form method="POST">
<input type="text" name="brn" placeholder="Branch"/>
<input type="text" name="nam" placeholder="Enter Name"/>
<input type="submit" name="insert">
<?php
$db=mysqli_connect("localhost","root","","test");
session_start();
if(isset($_POST['insert']))
{
$brn = $_POST['brn'];
$nam = $_POST['nam'];
$qry = "SELECT * FROM emp";
$result=mysqli_query($db,$qry);
$row = mysqli_fetch_array($result);
$empid= $row["empid"];
$empid++;
$query = "INSERT INTO `emp`(`brn`,`nam`,'empid') VALUES ('$brn','$nam','$empid')";
mysqli_query($db,$query);
mysqli_close($db);
}
?>
</form>
You need some changes in your code.
You are selecting the first "EmpId" instead of the last one and if you are having the column empid as primary key, it will show the error of primary key violation.
Therefore change your query to somewhat this:
$qry = "SELECT * FROM emp order by empid desc limit 1";
It will return one row.
And, if you just need the last empid then i would suggest you to go with only:
$qry = "SELECT empid FROM emp order by empid limit 1";
This is more resource effective query.
****Happy Coding.****
you can try this. I hope it will help you.
$sql = "INSERT INTO `emp`(`brn`,`nam`,'empid') VALUES ('$brn','$nam','$empid')";
if(mysqli_query($db, $sql)){
$last_id = mysqli_insert_id($db);
echo "Records inserted successfully. Last inserted ID is: " . $last_id;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

TextArea on form only taking a maximum of 50 characters?

When a user tries to enter a review in "textarea" in the form, only 50 characters of review is displayed. I have tried resolving the situation by disabling Jquery form validation changing the field type to tinytext, mediumtext. I am able to enter the full review 200 characters via PHPMyAdmin so I am guessing the problem is with my PHP but I am not able to see anything obvious . If any one could help it would be greatly appreciated.
<label for="review">Your Review</label>
<br/>
<textarea name="review" id="review" rows="15" cols="60"></textarea>
// Check for a review
if (empty($_POST['review'])){
$errors[] = "Please write a review";
} else {
$review = (trim($_POST['review']));
}
if (empty($errors)) { // If no errors were found.
require_once('./includes/mysql_connect.php');
// Make the insert query.
$query = "INSERT INTO films (movie_title, actor, rating, user_id)
Values ('$mt', '$la', '$rating', '$user')";
$result = mysql_query($query);
$id = mysql_insert_id();
$query = "INSERT INTO reviewed (review, movie_id)
values ('$review', '$id')";
$result = mysql_query($query);
<div id="Review_container">
<?php
require_once('./includes/mysql_connect.php');
$review = $_GET['id'];
echo $review;
?>
</div>
Table structure for table `reviewed`
CREATE TABLE IF NOT EXISTS `reviewed` (
`review_id` int(4) NOT NULL AUTO_INCREMENT,
`review` mediumtext NOT NULL,
`movie_id` int(4) NOT NULL,
PRIMARY KEY (`review_id`),
KEY `movie_id` (`movie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
//No value for review
if ($('#review').val() == "") {
$('.error').append("<li>Please enter a review</li>");
error = true;
}
if (error) { // If error found dont submit.
e.preventDefault();
}
}); // End of .submit function: review_a_film.php

PHP delete row via non PK

I have the user select a member ID, but I want it to delete the corresponding event ID (PK) so the row is just deleted. Can you suggest a simple and effective way of doing this? This is the code I am working on FYI.
Front end.
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Select member ID to <b> remove total and comment. </b>: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<input type="submit" value=">!DELETE!<" />
</form>
<?php
}
else
{
$mid = $_POST['meid'];
$db1 = new dbme();
$db1->openDB();
$numofrows = $db1->delete_total($meid);//basically kill off the entire row
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
Back end method
function delete_total($mid, $meid) {
$sql = "DELETE FROM memberevent WHERE mid = $mid"; // This is the bit I am head scratching, might there be a way to use mid to identify the corresponding PK (meid) to delete so the entire row is killed?
$result = mysqli_query($this->conn, $sql);
if ($result) {
$numofrows = mysqli_affected_rows($this->conn);
return $numofrows;
}
else
$this->error_msg = "could not connect for some wierd reason";
return false ;
}
P.S I am aware it cannot work in its current form.
Here's the memberevent table structure.
meid (PK auto incr INT)
mid (int)
total (varchar)
comments (varchar)
ename (varchar)

primary key and foreign key in php

Hi guys i really need some help down here with these primary keys and foreign keys.I've tried searching for leads but i'm not able to figure it out. Please help me out here and i'm sorry if this question has been asked before
i've got 2 tables and their columns
client
id(pk) | organisation | description | token
Transaction
trx_id | c_id(fk) | trx_description | trx_date | action | no_of_token
In the transaction table, all the values in it were manually key in by me through php myadmin even selecting the c_id which is the foreign key.so my question is for example i create a new organisation called ccc, i want it to get automatically assigned to the c_id of 3 in the transaction table.Also everytime i update the tokens, it should display in the trasaction table as trx_id(i already set it as auto increament)
but the c_id should match the organisation i've selected and increment the row accordingly.........Hope you guys can help me out quick and i'm sorry if i'm confusing you......I can post the code if you guys want :)
This script below add the client
<?php
include 'connection.php';
// Get values from form
$organisation=$_POST['organisation'];
$description=$_POST['description'];
$token=$_POST['token'];
// Insert data into mysql
$sql="INSERT INTO client(organisation, description, token)VALUES('$organisation', '$description', '$token')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='login_success.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
// close connection
mysql_close();
?>
transaction table script
<?php
include 'connection.php';
?>
<html>
<head>
<title>ThaiCreate.Com PHP & MySQL Tutorial</title>
</head>
<body>
<form action="add.php?id=<?=$_GET["id"];?>" name="frmEdit" method="POST">
<?
$strSQL = "SELECT * FROM client WHERE id = '".$_GET["id"]."' ";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
if(!$objResult)
{
echo "Not found id=".$_GET["id"];
}
else
{
?>
<table width="600" border="1">
<tr>
<th width="91"> <div align="center">id </div></th>
<th width="160"> <div align="center">organisation </div></th>
<th width="198"> <div align="center">current token </div></th>
</tr>
<tr>
<td><?=$objResult["id"];?></div></td>
<td><?=$objResult["organisation"];?></td>
<td><?=$objResult["token"];?></td>
</tr>
</table>
How many tokens do you want to add to this organisation: <input type="text" id="newToken" name="newToken" /><br/>
Please fill up the reason for adding the tokens : <input type="text" id="reason" name="reason" /><br/>
<input type="submit" name="submit" value="submit">
<?
$newToken = isset($_POST['newToken']) ? $_POST["newToken"] : "";
$reason = isset($_POST['reason']) ? $_POST["reason"] : "";
$sql="UPDATE client SET token = token + '$newToken' WHERE id = '".$_GET["id"]."' ";
$result=mysql_query($sql) or die ("Error Query [".$sql."]");
?>
<?
if ($newToken == true)
{
mysql_query("START TRANSACTION");
$date = date("Y-m-d H:i:s");
$query_string_count = "SELECT count(*) AS num FROM transaction WHERE c_id =" . $_GET["id"];
$query = mysql_query($query_string_count);
$result = mysql_fetch_array($objQuery);
$num = $objResult["num"];
INSERT INTO `transaction` (`trx_id`, `c_id`, `trx_description`, `trx_date`, `action`, `no_of_token`) VALUES ($num + 1, $_GET["id"], '$reason', '".$date."', 'Add token', '$newToken')";
mysql_query("COMMIT TRANSACTION");
?>
<?
header("Location:login_success.php");
}
else {
}
?>
<?
}
mysql_close();
?>
</form>
</body>
</html>
The problem is that you set up the trx_id as auotoincrement.
If you need keep separated the number of transcation of each client then the trx_id shouldn't be autoincrement.
For example each time you do insert on the transaction table:
1: start new transcation
2: number = count the number transactions that has as c_id the id of the client of interest
3: insert into transaction and set trx_id = number + 1
4: commit transaction
Note: in this case trx_id could not unique as you have more clients. If you need it you can insert a new column in the transaction table that is primary_key and in this case autoincrement
Here a snapshot of code to do what i described:
//new db transaction
mysql_query("START TRANSACTION");
// count number of transaction for clients $_GET["id"]
$query_string_count = "SELECT count(*) AS num FROM transactions WHERE c_id =" . $_GET["id"];
$query = mysql_query($query_string_count);
$result = mysql_fetch_array($objQuery);
$num = $objResult["num"];
//insert new transaction for client $_GET["id"] with id $num + 1
INSERT INTO `transaction` (`trx_id`, `c_id`, `trx_description`, `trx_date`, `action`, `no_of_token`) VALUES ($num + 1, $_GET["id"], '$reason', '".$date."', 'Add token', '$newToken')";
//COMMIT -> persist on db
mysql_query("COMMIT TRANSACTION");

Categories