Good day, please I created a page for payment when the payment is successful, all the Items the user purchased, which are the items in the cartItems should be sent to mySql data base. I am using PHP as my server.
The problem I encountered is that the I get try post the cartItems is said to be undefined and the when I echoed out cartItems I got null
Errors:
Array ( )
Warning: Undefined array key "cartItems" in C:xampphtdocsapiinsertOrders.php on line 14
Warning: Undefined variable $_cartItems in C:xampphtdocsapiinsertOrders.php on line 16
NULL
Warning: foreach() argument must be of type array|object, null given in C:xampphtdocsapiinsertOrders.php on line 23
Cart items inserted successfully!
so the items where not inserted
This is the Php code:
<?php
include 'connection.php';
// Prepare the SQL statement for inserting into orderProducts table
$insertOrderProductsStmt = $mysqli->prepare("INSERT INTO orders (userId, bookId, name, quantity, price) VALUES (?, ?, ?, ?,?)");
// $jsonPayload = file_get_contents('php://input');
// $data = json_decode($jsonPayload, true);
// Get the cart items from the request
print_r($_POST);
// if(isset($_POST['cartItems'])){
$cartItems = $_POST['cartItems'];
echo $cartItems;
var_dump($_cartItems);
// Start the transaction
$mysqli->begin_transaction();
try {
// Iterate over each cart item and execute the insert statement
foreach ($cartItems as $cartItem) {
$userId = $cartItem['userId'];
$bookId = $cartItem['bookId'];
$name = $cartItem['name'];
$quantity = $cartItem['quantity'];
$price = $cartItem['quantity'] * $cartItem['price'];
// Bind the parameters and execute the statement
$insertOrderProductsStmt->bind_param("iisii", $userId, $bookId, $name, $quantity, $price);
$insertOrderProductsStmt->execute();
}
// Commit the transaction
$mysqli->commit();
// Close the prepared statement
$insertOrderProductsStmt->close();
// Send a success response
echo "Cart items inserted successfully!";
} catch (Exception $e) {
// Rollback the transaction if an error occurred
$mysqli->rollback();
// Close the prepared statement
$insertOrderProductsStmt->close();
// Send an error response
echo "Error: " . $e->getMessage();
}
// Close the database mysqliection
$mysqli->close();
// }
// else{
// echo "an error occured";
// }
?>
This is my react native page :
the insertOrders is responsible for that and I called it in the onSuccess props of the Paystack component
import {
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
TextInput,
Alert,
} from "react-native";
import React, { useRef, useState } from "react";
import { cartTotalPriceSelector } from "../redux/selectors";
import { useDispatch, useSelector } from "react-redux";
import { color } from "react-native-reanimated";
import colors from "../config/colors";
import { clear } from "../redux/features/cart/cartSlice";
import { Paystack, paystackProps } from "react-native-paystack-webview";
const PaymentScreen = () => {
// const isValidEmail = (email) => {
// const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
// return emailRegex.test(email);
// };
const paystackWebViewRef = useRef(paystackProps.PayStackRef);
const totalPrice = useSelector(cartTotalPriceSelector);
const userId = useSelector((state) => state.user.userId);
const email = useSelector((state) => state.email.email);
const cart = useSelector((state) => state.cart);
const cartItems = cart.map((cartItem) => {
return {
userId: userId,
bookId: cartItem.bookId,
name: cartItem.name,
quantity: cartItem.quantity,
price: cartItem.price,
};
});
console.log("myItem",{ cartItems });
const insertOrders = () => {
const url = "http://192.168.11.102:80/api/insertOrders.php"; // Replace with the actual URL of your PHP page
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ cartItems }),
};
console.log("Before fetch request"); // Debugging statement
fetch(url, requestOptions)
.then((response) => {
console.log("Response received"); // Debugging statement
return response.json();
})
.then((result) => {
console.log("Result:", result); // Debugging statement
})
.catch((error) => {
console.error("Error:", error);
});
};
return (
<View style={styles.container}>
<Paystack
paystackKey="*****************************************"
billingEmail={email}
amount={totalPrice}
onCancel={(e) => {
// handle response here
}}
onSuccess={(res) => {
// handle response here
Alert.alert("Payment successful");
console.log("myItem",{ cartItems });
insertOrders();
}}
ref={paystackWebViewRef}
/>
<Image style={styles.image} source={require("../assets/payment.jpg")} />
<View style={styles.totalContainer}>
<Text style={styles.totalText}>₦{totalPrice}</Text>
<TouchableOpacity
style={styles.checkoutButton}
onPress={() => paystackWebViewRef.current.startTransaction()}>
<Text style={styles.checkoutButtonText}>Pay Now</Text>
</TouchableOpacity>
</View>
</View>
);
};
export default PaymentScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
checkoutButton: {
backgroundColor: colors.orange,
paddingHorizontal: 20,
paddingVertical: 10,
borderRadius: 20,
elevation: 3,
},
checkoutButtonText: {
fontSize: 16,
fontWeight: "bold",
color: "#FFFFFF",
},
image: {
width: 200,
height: 200,
resizeMode: "cover",
marginRight: 10,
borderRadius: 11,
},
totalContainer: {
margin: 10,
borderColor: colors.lightOrange,
borderWidth: 3,
borderRadius: 10,
padding: 20,
justifyContent: "center",
alignItems: "center",
},
totalText: {
fontSize: 18,
fontWeight: "bold",
},
emailInput: {
height: 40,
width: "100%",
borderColor: colors.lightOrange,
borderWidth: 2,
borderRadius: 5,
paddingHorizontal: 10,
marginTop: 10,
},
errorText: {
color: "red",
marginTop: 5,
},
});
when I console.log("myItems", {cartItems}) I got these response
myItem {"cartItems": [{"bookId": 18, "name": "The diary of a nigerian christian girl", "price": "2000.00", "quantity": 5, "userId": 31}, {"bookId": 21, "name": "A Time to Love", "price": "1500.00", "quantity": 3, "userId": 31}]}