У меня возникла проблема со вставкой данных в базу данных sqlite на выставке. Я использовал все доступные методы, которые знаю, но меня это просто не устраивает.
Я уже создал базу данных в своем файле App.js. Теперь я собираю информацию из переменной pins и отправляю их в мою базу данных (PHP). Дело в том, что я хочу иметь возможность сохранять их в своей базе данных SQLite также в режиме реагирования, чтобы я мог сравнивать данные на предмет соответствия.
Данные передаются в PHP, но это не так. вход в SQLITE. Вот мой код:
import React, { useState, useRef, useEffect } from 'react';
import { View, Text, TextInput, StyleSheet, TouchableOpacity, Button, SafeAreaView, Alert } from 'react-native';
import CheckBox from 'react-native-check-box';
import LoginStyle from './resources/styles/LoginStyle';
import axios from 'axios';
import AsyncStorage from "@react-native-async-storage/async-storage";
import * as SQLite from 'expo-sqlite/legacy';
import DbResources from "./resources/DbResources";
import { useNavigation } from '@react-navigation/native';
const db = SQLite.openDatabase("atlas.db");
/*
ALGORITHM
- First Check to make sure there is not already a user registered in the database.
* If there is, you should direct the person to the dashboard.
* else:
- Check if there is a phone number sent from the previous screen. Honestly, this doesn't have to be in the local storage, it can be passed as a prop.
* If there is, then use it as a registrations criteria, if there isn't the redirect the person to the previous state.
- In the event where there is no user in the database, you may just have to create one from the PIN and the phone number.
When you must have done this, save the information and send it back to the database.
*/
const CreatePinScreen = ({route}) => {
const navigation = useNavigation();
const [pin, setPin] = useState(['', '', '', '']);
const [isChecked, setIsChecked] = useState(false);
const [pinSet, setPinSet] = useState(false);
const [pinConfirm, setPinConfirm] = useState(['', '', '', '']);
const [accountAvailable, setAccountAvailable] = useState(false);
// const [phoneNumber, setPhoneNumber] = useState("");
const {phoneNumber} = route.params;
const [res, fetchDBR] = useState(null);
const [userData, setUserData] = useState({});
const inputs = useRef([]);
const inputsConfirm = useRef([]);
// CHECK FOR EXISTING USER
const CheckExisting = () =>{
db.transaction(tx => {
tx.executeSql(
`SELECT * FROM atlas_user_info;`,
[],
(_, { rows }) => {
const rowsArray = rows._array;
const quantity = rowsArray.length;
console.log("All rows in atlas_user_info:", rowsArray);
console.log("Quantity of items:", quantity);
if(rowsArray.length > 0){
setAccountAvailable(true);
}
},
(_, error) => {
console.error("Error selecting rows: ", error);
}
);
});
}
React.useEffect(()=>{
CheckExisting();
// SEND TO DASHBOARD IF THERE IS AN ACCOUNT
if(accountAvailable == true){
navigation.navigate("Authenticated");
}
}, []);
const handleChange = (text, index) => {
const newPin = [...pin];
newPin[index] = text;
setPin(newPin);
// Automatically focus next input
if (text && index < inputs.current.length - 1) {
inputs.current[index + 1].focus();
}else{
setPinSet(true);
}
};
useEffect(()=>{
const getRes = async()=>{
// const res = await DbResources("drop");
if(res != 0){
// fetchDBR(res);
// console.log(res);
}
}
getRes();
}, []);
const handleKeyPress = (e, index) => {
if (e.nativeEvent.key === 'Backspace' && pin[index] === '' && index > 0) {
inputs.current[index - 1].focus();
}
};
const handleChangeConfirm = (text, index) => {
const newPinC = [...pinConfirm];
newPinC[index] = text;
setPinConfirm(newPinC);
// Automatically focus next input
if (text && index < inputsConfirm.current.length - 1) {
inputsConfirm.current[index + 1].focus();
}else{
setPinSet(true);
}
};
const handleKeyPressConfirm = (e, index) => {
if (e.nativeEvent.key === 'Backspace' && pin[index] === '' && index > 0) {
inputsConfirm.current[index - 1].focus();
}
};
const deleteDatabase = async () => {
try {
await SQLite.deleteDatabaseAsync("atlasdb.db");
console.log('Database deleted successfully');
} catch (error) {
console.error('Failed to delete database:', error);
}
};
useEffect(()=>{
const continueOps = (rsData) =>{
const db = SQLite.openDatabase('atlas.db');
db.transaction(tx => {
tx.executeSql(
`SELECT * FROM atlas_user_info WHERE user_ac_token = ?;`,
[rsData.user_ac_token],
(_, { rows }) => {
console.log("All rows in atlas_user_info:", rows._array);
if(rows._array.length > 0){
navigation.navigate("Authenticated");
}else{
console.log("Something happened")
}
console.log(`Total selections: `, rows._array);
},
(_, error) => {
console.error("Error selecting rows: ", error);
}
);
});
};
const saveAccountInfo = () =>{
console.log(userData.pp_view);
// const db = SQLite.openDatabase('atlas.db');
// console.log(db);
let ppView = userData.pp_view;
let ppManage = userData.pp_manage;
let cbView = userData.cb_view;
let cbManage = userData.cb_manage;
let ivView = userData.iv_view;
let ivManage = userData.iv_manage;
let invView = userData.inv_view;
let invManage = userData.inv_manage;
// console.log(db);
db.transaction(tx => {
tx.executeSql(
`INSERT INTO atlas_user_info
(user_db_id, user_names, user_ac_token, user_ac_status, pp_view,
pp_manage, cb_view, cb_manage, iv_view, iv_manage, inv_view, inv_manage)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
rsData.user_id,
'',
rsData.user_token,
'',
ppView,
ppManage,
cbView,
cbManage,
ivView,
ivManage,
invView,
invManage
],
[],
() => {
console.log("Table created successfully");
// Query to list all tables
tx.executeSql(
`SELECT * FROM atlas_user_info`, null,
(txObj, resultSet) => console.log(resultSet.rows._array),
(txObj, error) =>console.log(error)
);
}
);
});
console.log('Why are we not getting to this point?');
continueOps(userData);
// navigation.navigate("Authenticated");
};
if(Object.entries(userData).length > 0){
saveAccountInfo();
}
}, [userData]);
const SignupUser = async ()=>{
const p1 = pin.join('');
const p1String = p1.toString();
const p2 = pinConfirm.join('');
const p2String = p2.toString();
if(p1 == ""){
Alert.alert('Please set your pin');
}else{
if(p1 != p2){
Alert.alert("Your Pins Do not match");
}else{
try{
let mode = "signup";
let priv = 'manager';
const dataToSend = {
'user_phone_number' : phoneNumber,
'user_pin' : p1,
'user_priv' : priv,
'mode': mode
};
const response = await axios.post('http://192.168.0.138/atlasbackend/apis/auth_api.php', dataToSend);
if(response != "0" && response.data!=0){
console.log(`data is: ${response.data}`);
setUserData(response.data);
}else{
console.log("Data is just zero");
}
// console.log(response.data);
}catch(error){
console.error("An error happened: " + error);
}
}
}
}
/*
*/
};
export default CreatePinScreen;
обратите особое внимание на функцию SaveAccountInfo, которая использует переменную состояния -> userData. вот в чем проблема. Спасибо за вашу помощь.
Я попробовал поместить код в хук useEffect, надеясь получить лучшие результаты, но безрезультатно. Я пробовал использовать openDatabaseAsync и openDatabaseSync, но безрезультатно. Поэтому я вернулся к этому методу. Таблицы базы данных создаются нормально, но данные не поступают.
У меня возникла проблема со вставкой данных в базу данных sqlite на выставке. Я использовал все доступные методы, которые знаю, но меня это просто не устраивает. Я уже создал базу данных в своем файле App.js. Теперь я собираю информацию из переменной pins и отправляю их в мою базу данных (PHP). Дело в том, что я хочу иметь возможность сохранять их в своей базе данных SQLite также в режиме реагирования, чтобы я мог сравнивать данные на предмет соответствия. Данные передаются в PHP, но это не так. вход в SQLITE. Вот мой код: [code]import React, { useState, useRef, useEffect } from 'react'; import { View, Text, TextInput, StyleSheet, TouchableOpacity, Button, SafeAreaView, Alert } from 'react-native'; import CheckBox from 'react-native-check-box'; import LoginStyle from './resources/styles/LoginStyle'; import axios from 'axios'; import AsyncStorage from "@react-native-async-storage/async-storage"; import * as SQLite from 'expo-sqlite/legacy'; import DbResources from "./resources/DbResources"; import { useNavigation } from '@react-navigation/native';
const db = SQLite.openDatabase("atlas.db");
/* ALGORITHM - First Check to make sure there is not already a user registered in the database. * If there is, you should direct the person to the dashboard. * else: - Check if there is a phone number sent from the previous screen. Honestly, this doesn't have to be in the local storage, it can be passed as a prop. * If there is, then use it as a registrations criteria, if there isn't the redirect the person to the previous state.
- In the event where there is no user in the database, you may just have to create one from the PIN and the phone number. When you must have done this, save the information and send it back to the database. */
[/code] обратите особое внимание на функцию SaveAccountInfo, которая использует переменную состояния -> userData. вот в чем проблема. Спасибо за вашу помощь. Я попробовал поместить код в хук useEffect, надеясь получить лучшие результаты, но безрезультатно. Я пробовал использовать openDatabaseAsync и openDatabaseSync, но безрезультатно. Поэтому я вернулся к этому методу. Таблицы базы данных создаются нормально, но данные не поступают.