SO i want to insert my item id and together with my item name into a distribution_item,it only insert item id but not the name because of the array
i use item[$i] whenever there is a item in the table row, so it get the data and insert.
#$recipient = $_POST['recipient'];
#$address = $_POST['address'];
#$contact = $_POST['contact'];
#$date = $_POST['in_date'];
#$itemID = $_POST['id'];
#$remark = $_POST['remark'];
#$spec_remark = $_POST['spec_remark'];
$itemBalance = $_POST["count"];
$count = count($itemID);
// authentication to the database
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "hopeplace";
//Create connection
$Conndb = mysqli_connect($servername, $username, $password, $dbName);
// Check connection
if (!$Conndb) {
die("Connection failed: " . $Conndb->connect_error);
}
else {
// select database
mysqli_select_db($Conndb, $dbName);
$full_name = "SELECT * FROM recipient WHERE `FULL_NAME` = '$recipient'";
$result = mysqli_query($Conndb, $full_name);
$rec = mysqli_fetch_array($result);
$recipient_id = $rec['HP_ID'];
$item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'";
$result2 = mysqli_query($Conndb, $item_id);
$rec2 = mysqli_fetch_array($result2);
$item_name = $rec2["ITEM_NAME"];
$string = implode(',',$item_id);
$sql = "SHOW TABLE STATUS WHERE `Name` = 'distribution';";
$result = mysqli_query($Conndb, $sql);
$data = mysqli_fetch_assoc($result);
$DISTRIBUTION_ID = $data['Auto_increment'];
// Add into distribution table
$sql = "INSERT INTO distribution(DISTRIBUTION_ID,HP_ID,FULL_NAME, ADDRESS, CONTACT, DISTRIBUTION_DATE, SPEC_REMARK) VALUES ('$DISTRIBUTION_ID','$recipient_id','$recipient', '$address', '$contact', '$date', '$spec_remark')";
if (mysqli_query($Conndb, $sql)) {
//Add item into distribution_item table
$item_count = 0;
for ($i=0; $i<$count; $i++){
$sql = "INSERT INTO distribution_item (DISTRIBUTION_ID, ITEM_ID,ITEM_NAME,OUT_QUANTITY,REMARK) VALUES ('$DISTRIBUTION_ID', '$itemID[$i]','$string[$i]','$itemBalance[$i]', '$remark[$i]')";
if (mysqli_query($Conndb, $sql)){
$out = "UPDATE inventory set QUANTITY = QUANTITY - '$itemBalance[$i]' where ITEM_ID= '$itemID[$i]'";
mysqli_query($Conndb, $out);
//echo "<p>Item $itemID[$i] has been added to $DISTRIBUTION_ID</p>";
$item_count++;
} else {
echo "Error: $sql <br />" . mysqli_error($Conndb);
}
}
if ($item_count == $count){
echo "<div>
<script>
window.alert('Record added successfully!');
</script>
</div>";
}
} else {
echo "Error: $sql <br />" . mysqli_error($Conndb);
}
}
mysqli_close($Conndb);
?>
it pop out an error like this
Notice: Array to string conversion in C:\xampp\htdocs\hopeplace\distribution\add_distribution.php on line 55
Warning: implode(): Invalid arguments passed in C:\xampp\htdocs\hopeplace\distribution\add_distribution.php on line 56
it seems like i have to convert my array to string so i can pass the value into table. my database table is something like this
DISTRIBUTION_ID | ITEM_NAME | ITEM_NAME|
1 1 APPLE
1 2 ORANGE
The problem here is that $string[$i] cannot be found because no $string array exists, since $string = implode(', ',$item_id) can only work if $item_id is an array.
In the question, $item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'"; gives $item_id as a string. That is why the warning error indicates that the implode function cannot work. The notice error shows that you cannot get an array element from the $string variable, and this is because that variable is not an array.
To get $string as an array, you would have to correct the following code:
$item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'";
$result2 = mysqli_query($Conndb, $item_id);
$rec2 = mysqli_fetch_array($result2);
$item_name = $rec2["ITEM_NAME"];
$string = implode(',',$item_id);
For example, the above code could be changed to the following:
$string = [];
$item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'";
$result2 = mysqli_query($Conndb, $item_id);
while($rec2 = mysqli_fetch_array($result2){
$string[] = $rec2["ITEM_NAME"];
}
Then in the sql query for inserting the item name you would first define the counting variable as $count = count($string);
Related
I have a 200 inputs ( 200 rows ) in my web page , the back end user some time enter 20 or 50 inputs and left the rest empty
how to prevent empty inputs from insertion to db
I get around that by deleting the rows with condition but is consuming time
this is my code
<?php
include("db.php");
include("header.php");
if (isset($_POST['invoice_btn'])) {
$userId = $_POST['userId'];
$invoice_to = $_POST['companyName'];
$subTotal = $_POST['subTotal'];
$taxAmount = $_POST['taxAmount'];
$taxRate = $_POST['taxRate'];
$totalAftertax = $_POST['totalAftertax'];
$amountPaid = $_POST['amountPaid'];
$amountDue = $_POST['amountDue'];
$notes = $_POST['notes'];
$productCode = $_POST['productCode'];
$productName = $_POST['productName'];
$quantity = $_POST['quantity'];
$price = $_POST['price'];
$total = $_POST['total'];
$dateTime = $_POST['dateTime'];
$submitbutton = $_POST['invoice_btn'];
if ($submitbutton) {
if (empty($productCode)) {
die(" Product code empty ");
} else {
$sqlInsert = "INSERT INTO invoice_order (invoice_to,order_date, order_total_before_tax, order_total_tax, order_tax_per, order_total_after_tax, order_amount_paid, order_total_amount_due, notes)
VALUES ('$invoice_to' ,'$dateTime', '$subTotal', '$taxAmount','$taxRate', '$totalAftertax','$amountPaid', '$amountDue','$notes')";
$result = mysqli_query($conn, $sqlInsert);
// The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.
$lastInsertId = mysqli_insert_id($conn);
foreach ($productCode as $index => $productCodes) {
$s_productCode = $productCodes;
$s_productName = $productName[$index];
$s_quantity = $quantity[$index];
$s_price = $price[$index];
$s_total = $total[$index];
$sqlInsertItem = "INSERT INTO invoice_order_item (order_id, item_code, item_name, order_item_quantity, order_item_price, order_item_final_amount)
VALUES ( '$lastInsertId' , '$s_productCode' , '$s_productName' , '$s_quantity', '$s_price', '$s_total')";
$result2 = mysqli_query($conn, $sqlInsertItem);
// Update Quantity on Hand from Produc table
$sqlUpdateQty = "UPDATE product SET pro_quantity = pro_quantity-$s_quantity WHERE pro_id = $s_productCode ";
$result3 = mysqli_query($conn, $sqlUpdateQty);
//delete extra rows that are empty .
$sqlDelete = "DELETE FROM `invoice_order_item` WHERE `item_code`=''";
$Delresult = mysqli_query($conn, $sqlDelete);
} // end foreach
}; // end else
} // end if
In your foreach loop, add a condition before the insertion:
if (empty($s_productCode)) continue;
If the condition becomes true, continue will make the parser skip the rest of the code in the loop.
I'm trying to make a Check-in/out system.
So far I have a dropdown that get the list of active events.
<select name="events">
<?php
$conn = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
$eveny = $conn->query("select event_title from events_event where inactive=0");
while ($row=mysqli_fetch_array($eveny)) {
unset($event);
$event = $row['event_title'];
echo '<option value="'.$event.'">'.$event.'</option>';
}
?>
</select>
And a textbox that searches users based on first name, but it auto displays results (like a Google search) and then fills out the info with both First Name and Last name. Source.
The only change in the php is the echo to show both first and last names as follows:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["per_FirstName"] . " " . $row["per_LastName"] . "</p>";
}
NOW FOR THE PROBLEM
I have made the frontend into a form, and a submit button using method="post".
But something in my php is not functioning/lacking.
<?php
$db = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myname = mysqli_real_escape_string($db,$_POST['fullname']);
$eventy = mysqli_real_escape_string($db,$_POST['events']);
//$checktime = mysqli_real_escape_string($db,date("Y-m-d H:i:s"));
$evid = "SELECT event_id from events_event where event_title = '$eventy'";
$revvy = mysqli_query($db,$evid);
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);
$lastName = trim($nameParts[1]);
$sql = "SELECT per_ID FROM person_per WHERE per_FirstName = '$firstName' AND per_LastName = '$lastName'";
$result = mysqli_query($db,$sql);
//$row = mysqli_fetch_row($result);
//$result = $result->fetch_all();
while($row = mysqli_fetch_assoc($result)){
$perID = $row['per_ID'];
}
while($row2 = mysqli_fetch_assoc($revvy)){
$evvy = $row['event_ID'];
}
$count = mysqli_num_rows($result);
// table row must be 1 row if it succeeded
if($count == 1) {
//session_register("myname");
//$_SESSION['login_user'] = $myname;
$checkin = "insert into event_attend (attend_id, event_id, person_id, checkin_date) values (DEFAULT, '$evvy', '$perID', now())" or die(mysqli_error());;
mysqli_query($db,$checkin);
header("location: checkedin.php");
}else {
$error = "An error occurred.";
}
}
?>
The $myname, is the result of both first name and last name, I need just First Name based on the filled out text field which uses both first and last names.
I also can't get the Event_ID from the dropdown.
If user's first and last name are separated by space:
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);
I am trying to only allow a submission via the form only if a party_id exists in a table using empty, here is my code at the moment it is still allowing everything through even if there is no party_id.
Any help would be great.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='" . $party_id . "'";
$res = mysqli_query($link, $sql);
if(empty($party_id)) { #Were any records found?
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
A simpler way might be to just check if the query returned any results like this.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='$party_id'";
$res = mysqli_query($link, $sql);
if ( mysqli_num_rows($res ) == 0 ) {
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
How can I concatenate two columns in where clause
this is my normal query:
$result = mysql_query("SELECT stud_id FROM tb_student WHERE instructor_id = '$instructor_id' AND description = '$description' AND stud_fname = '$stud_fname' AND stud_lname = '$stud_lname'") or die(mysql_error());
I want the stud_fname and stud_lname to be concatenated.
here is my full code:
<?php
error_reporting(0);
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect");
mysql_select_db("dbmobile_class_record") or die("Could not select database");
// array for JSON response
$response = array();
$instructor_id=$_GET['instructor_id'];
$description=$_GET['description'];
$stud_fname=$_GET['stud_fname'];
$stud_lname=$_GET['stud_lname'];
// get all items from myorder table
$result = mysql_query("SELECT stud_id FROM tb_student WHERE instructor_id = '$instructor_id' AND description = '$description' AND stud_fname = '$stud_fname' AND stud_lname = '$stud_lname'") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["student"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$student = array();
$student["stud_id"] = $row["stud_id"];
// push ordered items into response array
array_push($response["student"], $student);
}
// success
$response["success"] = 1;
}
else {
// order is empty
$response["success"] = 0;
$response["message"] = "No Records Found";
}
// echoing JSON response
echo json_encode($response);
?>
$instructor_id = $_GET['instructor_id'];
$description = $_GET['description'];
$fullname = $_GET['fullname'];
// get all items from myorder table
$result = mysql_query("SELECT stud_id FROM tb_student WHERE instructor_id = '$instructor_id' AND description = '$description' AND CONCAT(stud_fname, ' ', stud_lname) = '$fullname'") or die(mysql_error());
Use this one
$result = mysql_query("SELECT stud_id, CONCAT_WS('', stud_fname, stud_lname) AS stud_fullname FROM tb_student WHERE instructor_id = '$instructor_id' AND description = '$description' AND stud_fname = '$stud_fname' AND stud_lname = '$stud_lname'") or die(mysql_error());
stud_fullname should contain what you want.
Hi i am having an issue selecting a value form my table into a variable in the PHP so that I can calculate the cost of something
here is the code I have so far I want to be able to select a "cost" value from the table C_price where the values of I_type and a_type match
E.g. the table structure looks like this
ID=1,A_type=line,I_type=Head,cost=5
if on the form i enter line and head
i need to be able to get the value 5 in to a venerable i can use in calculations and insert into another table AKA i need to get cost into a variable somehow
the following was my try and i need help im new at all this so please help
$E_C;
$T_cost = "1";
$date = date("d.m.y");
$name = $_POST["from"];
$email = $_POST["email"];
$ref = $_POST["link"];
$i_type = $_POST["i_type"];
$a_type = $_POST["a_type"];
$extra = $_POST["extra"];
$des = $_POST["description"];
$BG = $_POST["BG"];
$bg_type = $_POST["BGtype"];
$msg = $_POST["message"];
$auto_reply = ("thanks for the email we will get back to you as soon as we can about the cost and how you can pay");
$msg = wordwrap($msg, 70);
$host = "localhost";// hostname
$USER = "root";// username
$PASS = "Password";// password
$DBNAME = "andrea";// databace name
$tbl_name = "c_price";// table name
$con = mysqli_connect("localhost", $USER, $PASS, $DBNAME)or die("mySQL server connection failed");
$all = "SELECT cost FROM C_price WHERE a_type=$a_type,i_type=$i_type";
$result = mysqli_query($con,$all) or die("Error getting total storse");
while($row = mysqli_fetch_array($result))
{
echo $row['cost'];
}
if ($a_type = 'waist' && $extra='Y')
{
$E_C = $cost * .3;
}
elseif ($a_type = 'knee' && $extra='Y')
{
$E_C = $cost * .35;
}
elseif ($a_type ='full' && $extra='Y')
{
$E_C = $cost * .4;
}
else
{
$E_C = 0;
}
$T_cost = $cost + $E_C;
if ($BG = 'y')
{
$T_cost = $T_cost + 10;
}
You can't use mysqli and mysql at a same time.. Mysqli is a class... So first change that things...
while($row = mysqli_fetch_array($result))
{
echo $row['cost'];
}
$news1 = mysqli_result($result, 0); // 0 is the index of the field, not the row
echo $news1;
echo $cost;`
Query should be like this...
$all = "SELECT cost FROM C_price WHERE a_type='$a_type'and i_type='$i_type'";
You cant mix mysql and mysqli
change this line In the while loop and add for error mysqli_error
$news1 = mysql_result($result, 0);
$news1 = mysqli_result($result) or die(mysqli_error());
and your query is wrong as well and A_type is not same as A_type and same goes for I_type as well
$all = "SELECT cost FROM C_price WHERE a_type=$a_type,i_type=$i_type";
//Change it to
$all = "SELECT cost FROM C_price WHERE A_type='$a_type'and I_type='$i_type'";
//and A_type is not same as a_type and same goes for I_type as well