Я очень новичок в MySQL и PHP. Я пытаюсь написать приложение для iOS для практики, которое в основном перечисляет книги в базу данных путем «перечисления». Вот изображение моей таблицы для списков в базе данных:
Isbn является глобальной переменной. Я уверен, что это не проблема. Происходит много странных вещей, и я не могу понять, в чем проблема. Иногда код будет работать так, как я планировал, и новый список будет успешно добавлен в мою таблицу. В других случаях это не добавляет строку вообще. Когда я NSLog dataURL, он отображает (ноль) для времени, когда он работает, и он отображает <> Для времен это работает или частично работает. Я говорю, что частично работает, потому что иногда по какой-то причине он не введет весь код deleteCode в таблицу базы данных. Он будет вводить все нормально, кроме deleteCode, и в этом случае он иногда вводит случайное число цифр. Он всегда должен быть длиной 20 символов, но иногда он входит только в первый символ, в другой раз он вводится в 10 символов, в другой раз он вводится в 18 символов … это очень странно. Когда я делаю NSLog deleteCode, он ВСЕГДА отображает правильный 20-значный символ deleteCode, но он не всегда вводится в базу данных … Пожалуйста, помогите мне, я сбит с толку 🙁 Вот мой код iOS:
#import "ListBookViewController.h"#include <unistd.h>
#include <netdb.h>
NSString *isbnSelling;
@interface ListBookViewController ()
@end
@implementation ListBookViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
codeToDeleteBook = [self generateDeleteCode];
NSLog(@"%@", codeToDeleteBook);
self.priceTextField.autocorrectionType = UITextAutocorrectionTypeNo;
self.emailTextField.autocorrectionType = UITextAutocorrectionTypeNo;
self.phoneTextField.autocorrectionType = UITextAutocorrectionTypeNo;
self.conditionTextField.autocorrectionType = UITextAutocorrectionTypeNo;
self.listBookButton.layer.cornerRadius = 20;
self.listBookButton.layer.borderColor=[UIColor blackColor].CGColor;
self.listBookButton.layer.borderWidth= 2.0f;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];
tap.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tap];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)isValidEmail:(NSString *)checkString
{
BOOL stricterFilter = NO;
NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:checkString];
}
- (IBAction)listBookButtonPressed:(id)sender
{
// Making sure price is valid
self.priceTextField.text = [self.priceTextField.text stringByReplacingOccurrencesOfString:@"$" withString:@""];
self.priceTextField.text = [self.priceTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
if ([self.priceTextField.text rangeOfString:@"."].location != NSNotFound)
{
self.errorLabel.text = @"Price must be rounded by the dollar. EXAMPLE: 50";
return;
}
NSScanner* scan = [NSScanner scannerWithString:self.priceTextField.text];
int val;
if([scan scanInt:&val] && [scan isAtEnd])
{
if([self.priceTextField.text intValue] > 999)
{
self.errorLabel.text = @"Maximum price to list a book at is $999.";
return;
}
}
else
{
self.errorLabel.text = @"Invalid price.";
return;
}// Making sure email address is valid
self.emailTextField.text = [self.emailTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
if(![self isValidEmail:self.emailTextField.text])
{
self.errorLabel.text = @"Invalid email.";
return;
}
if([self.emailTextField.text length] > 49)
{
self.errorLabel.text = @"Email must be smaller than 50 characters.";
return;
}// Making sure phone number is valid
self.phoneTextField.text = [self.phoneTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
self.phoneTextField.text = [self.phoneTextField.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSScanner *scan2 = [NSScanner scannerWithString:self.phoneTextField.text];
int val2;
if(!([scan2 scanInt:&val2] && [scan2 isAtEnd]))
{
if(![self.phoneTextField.text isEqualToString:@""] && ![self.phoneTextField.text isEqualToString:@"N/A"])
{
self.errorLabel.text = @"Invalid phone number.";
return;
}
}
self.errorLabel.text = @"";
if([self.phoneTextField.text isEqualToString:@""])
self.phoneTextField.text = @"N/A";if([self internetReachable])
{
[self.priceTextField setEnabled:false];
[self.emailTextField setEnabled:false];
[self.phoneTextField setEnabled:false];
[self.conditionTextField setEnabled:false];
[self.listBookButton setEnabled:false];if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
if([[UIDevice currentDevice] isMultitaskingSupported])
{
UIApplication *application = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Entering data into Listings table
NSString *strURL = [NSString stringWithFormat:@"http://example.org/addListing.php?deleteCode=%@&isbn13=%@&price=%@&email=%@&phone=%@&condition=%@", codeToDeleteBook ,isbnSelling ,self.priceTextField.text, self.emailTextField.text, self.phoneTextField.text, self.conditionTextField.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSLog(@"%@", dataURL);
// Entering data into ContactInfo table
NSString *strURL2 = [NSString stringWithFormat:@"http://example.org/addContactInfo.php?email=%@&phone=%@", self.emailTextField.text, self.phoneTextField.text];
NSData *dataURL2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL2]];[application endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;dispatch_async(dispatch_get_main_queue(), ^{
self.bookListedImage.hidden = false;
self.deleteCodeLabel.hidden = false;
self.deleteCodeLabel.text = codeToDeleteBook;
});
});
}
}
}
else
{
self.errorLabel.text = @"Could not connect to internet.";
}
}
- (IBAction)startedEditingPriceTextField:(id)sender
{
self.listBookButton.hidden = true;
}
- (IBAction)startedEditingEmailTextField:(id)sender
{
self.listBookButton.hidden = true;
}
- (IBAction)startedEditingPhoneTextField:(id)sender
{
self.listBookButton.hidden = true;
}
- (IBAction)startedEditingConditionTextField:(id)sender
{
self.listBookButton.hidden = true;
}
- (IBAction)doneEditingPriceTextField:(id)sender
{
self.listBookButton.hidden = false;
}
- (IBAction)doneEditingEmailTextField:(id)sender
{
self.listBookButton.hidden = false;
}
- (IBAction)doneEditingPhoneTextField:(id)sender
{
self.listBookButton.hidden = false;
}
- (IBAction)doneEditingConditionTextField:(id)sender
{
self.listBookButton.hidden = false;
}
-(void)dismissKeyboard
{
self.listBookButton.hidden = false;
[self.priceTextField resignFirstResponder];
[self.emailTextField resignFirstResponder];
[self.phoneTextField resignFirstResponder];
[self.conditionTextField resignFirstResponder];
}
-(NSString *)generateDeleteCode
{
NSString *deleteCode = @"";
for(int i = 0; i < 20; i++)
{
NSInteger randomNumber = arc4random() % 62; // generates random number between 0 and 61 (62 different random characters)
switch(randomNumber)
{
case 0:
deleteCode = [deleteCode stringByAppendingString:@"0"];
break;
case 1:
deleteCode = [deleteCode stringByAppendingString:@"&"];
break;
case 2:
deleteCode = [deleteCode stringByAppendingString:@"2"];
break;
case 3:
deleteCode = [deleteCode stringByAppendingString:@"3"];
break;
case 4:
deleteCode = [deleteCode stringByAppendingString:@"4"];
break;
case 5:
deleteCode = [deleteCode stringByAppendingString:@"5"];
break;
case 6:
deleteCode = [deleteCode stringByAppendingString:@"6"];
break;
case 7:
deleteCode = [deleteCode stringByAppendingString:@"7"];
break;
case 8:
deleteCode = [deleteCode stringByAppendingString:@"8"];
break;
case 9:
deleteCode = [deleteCode stringByAppendingString:@"9"];
break;
case 10:
deleteCode = [deleteCode stringByAppendingString:@"q"];
break;
case 11:
deleteCode = [deleteCode stringByAppendingString:@"w"];
break;
case 12:
deleteCode = [deleteCode stringByAppendingString:@"e"];
break;
case 13:
deleteCode = [deleteCode stringByAppendingString:@"r"];
break;
case 14:
deleteCode = [deleteCode stringByAppendingString:@"t"];
break;
case 15:
deleteCode = [deleteCode stringByAppendingString:@"y"];
break;
case 16:
deleteCode = [deleteCode stringByAppendingString:@"u"];
break;
case 17:
deleteCode = [deleteCode stringByAppendingString:@"i"];
break;
case 18:
deleteCode = [deleteCode stringByAppendingString:@"o"];
break;
case 19:
deleteCode = [deleteCode stringByAppendingString:@"p"];
break;
case 20:
deleteCode = [deleteCode stringByAppendingString:@"a"];
break;
case 21:
deleteCode = [deleteCode stringByAppendingString:@"s"];
break;
case 22:
deleteCode = [deleteCode stringByAppendingString:@"d"];
break;
case 23:
deleteCode = [deleteCode stringByAppendingString:@"f"];
break;
case 24:
deleteCode = [deleteCode stringByAppendingString:@"g"];
break;
case 25:
deleteCode = [deleteCode stringByAppendingString:@"h"];
break;
case 26:
deleteCode = [deleteCode stringByAppendingString:@"j"];
break;
case 27:
deleteCode = [deleteCode stringByAppendingString:@"k"];
break;
case 28:
deleteCode = [deleteCode stringByAppendingString:@"*"];
break;
case 29:
deleteCode = [deleteCode stringByAppendingString:@"z"];
break;
case 30:
deleteCode = [deleteCode stringByAppendingString:@"x"];
break;
case 31:
deleteCode = [deleteCode stringByAppendingString:@"c"];
break;
case 32:
deleteCode = [deleteCode stringByAppendingString:@"v"];
break;
case 33:
deleteCode = [deleteCode stringByAppendingString:@"b"];
break;
case 34:
deleteCode = [deleteCode stringByAppendingString:@"n"];
break;
case 35:
deleteCode = [deleteCode stringByAppendingString:@"m"];
break;
case 36:
deleteCode = [deleteCode stringByAppendingString:@"Q"];
break;
case 37:
deleteCode = [deleteCode stringByAppendingString:@"W"];
break;
case 38:
deleteCode = [deleteCode stringByAppendingString:@"E"];
break;
case 39:
deleteCode = [deleteCode stringByAppendingString:@"R"];
break;
case 40:
deleteCode = [deleteCode stringByAppendingString:@"T"];
break;
case 41:
deleteCode = [deleteCode stringByAppendingString:@"Y"];
break;
case 42:
deleteCode = [deleteCode stringByAppendingString:@"U"];
break;
case 43:
deleteCode = [deleteCode stringByAppendingString:@"%"];
break;
case 44:
deleteCode = [deleteCode stringByAppendingString:@"$"];
break;
case 45:
deleteCode = [deleteCode stringByAppendingString:@"P"];
break;
case 46:
deleteCode = [deleteCode stringByAppendingString:@"A"];
break;
case 47:
deleteCode = [deleteCode stringByAppendingString:@"S"];
break;
case 48:
deleteCode = [deleteCode stringByAppendingString:@"D"];
break;
case 49:
deleteCode = [deleteCode stringByAppendingString:@"F"];
break;
case 50:
deleteCode = [deleteCode stringByAppendingString:@"G"];
break;
case 51:
deleteCode = [deleteCode stringByAppendingString:@"H"];
break;
case 52:
deleteCode = [deleteCode stringByAppendingString:@"J"];
break;
case 53:
deleteCode = [deleteCode stringByAppendingString:@"K"];
break;
case 54:
deleteCode = [deleteCode stringByAppendingString:@"L"];
break;
case 55:
deleteCode = [deleteCode stringByAppendingString:@"Z"];
break;
case 56:
deleteCode = [deleteCode stringByAppendingString:@"X"];
break;
case 57:
deleteCode = [deleteCode stringByAppendingString:@"C"];
break;
case 58:
deleteCode = [deleteCode stringByAppendingString:@"V"];
break;
case 59:
deleteCode = [deleteCode stringByAppendingString:@"B"];
break;
case 60:
deleteCode = [deleteCode stringByAppendingString:@"N"];
break;
case 61:
deleteCode = [deleteCode stringByAppendingString:@"M"];
break;
default:
deleteCode = [deleteCode stringByAppendingString:@"?"];
break;
}
}
return deleteCode;
}
- (BOOL)internetReachable
{
char *hostname;
struct hostent *hostinfo;
hostname = "example.org";
hostinfo = gethostbyname(hostname);
if (hostinfo == NULL)
return false;
else
return YES;
}
@end
Ниже мой PHP и MySQL код:
<?php
$con=mysqli_connect("localhost","editedOut","editedOut","editedOut");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$deleteCode = $_GET["deleteCode"];
$isbn13 = $_GET["isbn13"];
$price = $_GET["price"];
$email = $_GET["email"];
$phone = $_GET["phone"];
$condition = $_GET["condition"];
mysqli_query($con,"INSERT INTO Listings
VALUES ('$deleteCode', (NOW() + INTERVAL 2 HOUR), '$isbn13', $price, '$email', '$phone', '$condition')");
mysqli_close($con);
?>
Задача ещё не решена.
Других решений пока нет …