I have a csv upload script that works perfectly on my PC and other PC's have been tested as well. I have a client who is trying this script on their Mac and it returns an error: Error no file selected.
The permissions on the upload folder are 755.
Really need to find out the cause of this. You can see my script and form below.
define("UPLOAD_DIR", "/home/path/public_html/uploads/".$company."/");
$message = null;
$allowed_extensions = array('csv');
if(!empty($_FILES['file'])){
if($_FILES['file']['error'] === 0){
$file = explode(".", $_FILES['file']['name']);
$extension = array_pop($file);
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $_FILES['file']["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
if(in_array($extension, $allowed_extensions)){
if(move_uploaded_file($_FILES['file']['tmp_name'],
UPLOAD_DIR . $name)){
if(($handle = fopen(UPLOAD_DIR . $name, "r")) !== false){
$keys = array();
$out = array();
$line =1;
while(($row = fgetcsv($handle, 0, ',', '"')) !== false){
foreach($row as $key => $value){
if($line === 1){
$keys[$key] = $value;
}else{
$out[$line][$key] = $value;
}
}
$line++;
}
fclose($handle);
if(!empty($keys) && !empty($out)){
foreach($out as $key => $value){
$sql = "INSERT INTO ".$company."(id,prefix,fullname,last_name,business,address1,address2,address3,town,county,postcode,email,website,telephone1,telephone2,telephone3,landing_page,assigned_to,question1,question2,question3,question4,question5,question6,date,status,leadtype,file,gclid,leadid,tostep,ip,client_xp)VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$date = date("Y-m-d H:i:s");
$status = "New Lead";
$client_xp = 1;
$statement = $db->prepare($sql);
$statement->bindParam(1, $value[0], PDO::PARAM_STR);
$statement->bindParam(2, $value[1], PDO::PARAM_STR);
$statement->bindParam(3, $value[2], PDO::PARAM_STR);
$statement->bindParam(4, $value[3], PDO::PARAM_STR);
$statement->bindParam(5, $value[4], PDO::PARAM_STR);
$statement->bindParam(6, $value[5], PDO::PARAM_STR);
$statement->bindParam(7, $value[6], PDO::PARAM_STR);
$statement->bindParam(8, $value[7], PDO::PARAM_STR);
$statement->bindParam(9, $value[8], PDO::PARAM_STR);
$statement->bindParam(10, $value[9], PDO::PARAM_STR);
$statement->bindParam(11, $value[10], PDO::PARAM_STR);
$statement->bindParam(12, $value[11], PDO::PARAM_STR);
$statement->bindParam(13, $value[12], PDO::PARAM_STR);
$statement->bindParam(14, $value[13], PDO::PARAM_STR);
$statement->bindParam(15, $value[14], PDO::PARAM_STR);
$statement->bindParam(16, $value[15], PDO::PARAM_STR);
$statement->bindParam(17, $value[16], PDO::PARAM_STR);
$statement->bindParam(18, $value[17], PDO::PARAM_STR);
$statement->bindParam(19, $value[18], PDO::PARAM_STR);
$statement->bindParam(20, $value[19], PDO::PARAM_STR);
$statement->bindParam(21, $value[20], PDO::PARAM_STR);
$statement->bindParam(22, $value[21], PDO::PARAM_STR);
$statement->bindParam(23, $value[22], PDO::PARAM_STR);
$statement->bindParam(24, $value[23], PDO::PARAM_STR);
$statement->bindParam(25, $date, PDO::PARAM_STR);
$statement->bindParam(26, $status, PDO::PARAM_STR);
$statement->bindParam(27, $value[26], PDO::PARAM_STR);
$statement->bindParam(28, $value[27], PDO::PARAM_STR);
$statement->bindParam(29, $value[28], PDO::PARAM_STR);
$statement->bindParam(30, $value[29], PDO::PARAM_STR);
$statement->bindParam(31, $value[30], PDO::PARAM_STR);
$statement->bindParam(32, $value[31], PDO::PARAM_STR);
$statement->bindParam(33, $client_xp, PDO::PARAM_STR);
$statement->execute();
}
$message = '
<div class="row">
<div class="col-lg-6">
<div class="alert alert-success">
Success. Import complete. <i class="fa fa-times pull-right"></i>
</div>
</div>
</div>';
}
}
}
} else {
$message = '
<div class="row">
<div class="col-lg-6">
<div class="alert alert-warning">
Only CSV\'s allowed <i class="fa fa-times pull-right"></i>
</div>
</div>
</div>';
}
} else {
$message = '
<div class="row">
<div class="col-lg-6">
<div class="alert alert-warning">
There was a problem with your upload. Please try again. <i class="fa fa-times pull-right"></i>
</div>
</div>
</div>';
}
}
<form enctype="multipart/form-data" method="POST" action="/import/">
<div class="form-body pal">
<div class="row">
<div class="col-md-12">
<div class="form-group">
CSV file to import:<br /><br /><input type="file" name="file" id="file">
</div>
</div>
</div>
<input type="submit" name="submit" class="btn btn-blue" value="Upload">
</div>
</form>
Ok so this ended up being a really simple solution by changing the first line of code to this
define("UPLOAD_DIR", "/home/path/public_html/uploads/$company/");
The inverted commas were closing the string before the company variable could be used, making the upload path invalid.
Related
I am trying to create a script which uploads an electronic signature to the customers record, I am getting the ID but am not able to create the entry on the database and there is no error message being produced in the logs, simply refreshes the page.
Here is what I have so far.
Code
<?php
include '../../main.php';
check_loggedin($pdo);
$msg = null;
$date = new DateTime();
$totay_date = $date->format('Y-m-d\TH:i:s');
$folderPath = "upload/";
$image_parts = explode(";base64,", $_POST['signature']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . $name . "_" . uniqid() . '.' . $image_type;
file_put_contents($file, $image_base64);
if (isset($_GET['id'])) {
$stmt = $pdo->prepare('SELECT * FROM contacts WHERE id = ?');
$stmt->execute([$_GET['id']]);
$contact = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare('SELECT id,username FROM accounts');
$stmt->execute();
$all_account_info = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(isset($_POST['$name']) == null || isset($_POST['$file'])){
$msg = '';
}else{
$id = isset($_POST['id']) && !empty($_POST['id']) && $_POST['id'] != 'auto' ? $_POST['id'] : auto;
$stmt = $pdo->prepare('INSERT INTO esign VALUES (?, ?, ?, ?)');
$result = $stmt->execute([$id, $_GET['id'], $_POST['name'], $_POST['$file']]);
$msg = "Signature has been recorded.";
}
if (!$contact) {
exit('Help');
}
} else {
exit('No ID specified!');
}
?>
Form
<form action="add-sig.php?id=<?=$contact['id']?>" method="post">
<h1>Signature Pad</h1>
<div class="col-md-12">
<label class="form-label" for="name">Name</label> <input class="form-control" id="name" name="name" required="" type="text">
</div>
<div class="col-md-12">
<label class="" for="">Signature:</label><br>
<div id="sig"></div><br>
<textarea id="signature64" name="signature" style="display: none"></textarea>
<div class="col-12">
<button class="btn btn-sm btn-warning" id="clear">⌫Clear Signature</button>
</div>
</div><br>
<button class="btn btn-success" name="submit" type="submit">Submit</button>
</form>
</div>
Database
`id` int(11) NOT NULL,
`client_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`signature_img` varchar(255) NOT NULL
It loads the ID when clicking add signature and the address link looks something like add-sig.php?id=29 when accessing the page from the clients record page.
When I am in the clients record, I would like to be able to view the signature on their record.
The form converts the signature into an image file.
I have a script that was working perfectly but I cannot see the error. The script has two functions. The first is to create a new client in the database, which works perfectly. The second part of the script (near the bottom) is to update the database for the client if they exist.
The page sends the client ID to make the edits, but somewhere is this script it stops responding. When submitted, the view-client.php page loads, but the URL displays 'client=Array', not for example 'client=1'. I think I have narrowed it down to the PHP that controls the new password entered on registration, both called $password and $passKey.
This is meant to save the updated data to the database and redirect the user upon submit to the view-client.php page with the correct ID. Any help is greatly appreciated!
EDIT
Form and script for reference...
<?PHP
include('../core/init.php');
require_once('dbConfig.php');
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 5; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
//$generatedId = "SPI-E7HN2SBIIF5W";
$generatedId = 'SPI-'.$randomString;
//Prepare select query
$statement = $db->prepare("SELECT client_unique_id FROM clients WHERE client_unique_id = ? LIMIT 1");
//Determine variable and then bind that variable to a parameter for the select query ?
$id = $generatedId;
$statement->bind_param('s', $id);
//Execute and store result so that num_rows returns a value and not a 0
$statement->execute();
$statement->store_result();
//Bind result to a variable for easy management afterwards
$statement->bind_result($clientId);
// Generate a random ID for the user if the previously generated one already exists
if($statement->num_rows > 0) {
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 0; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$generatedId = 'SPI-'.$randomString;
//echo $generatedId;
}
$client = $_POST['createClientId'];
$insertId = $_POST['insertId'];
$passKey = $_POST['PassKey'];
$firstName = $_POST['FirstName'];
$surname = $_POST['Surname'];
$businessName = $_POST['BusinessName'];
$addressLine1 = $_POST['AddressLine1'];
$addressLine2 = $_POST['AddressLine2'];
$townCity = $_POST['TownCity'];
$county = $_POST['County'];
$postcode = $_POST['Postcode'];
$telephone = $_POST['Telephone'];
$mobile = $_POST['Mobile'];
$userName = $_POST['Username'];
$accountType = $_POST['AccountType'];
$email = $_POST['EmailAddress'];
$password = $_POST['Password'];
$additionalInfo = $_POST['AdditionalInformation'];
foreach($passKey as $key => $val) {
if($password[$key] == '' || !$password[$key]){
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 18; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$generatedPassword = $randomString;
/* Two create a Hash you do */
$password = $bcrypt->genHash($generatedPassword);
//$password = sha1($generatedPassword);
} else {
$password = $bcrypt->genHash($password[$key]);
//$password = sha1($password[$key]);
}
if(!$client[$key]) {
if($_SESSION['member_unique_id']=="supermember") {
$member_unique_ids="ISPI-ADMIN";
} else {
$member_unique_ids = $_SESSION['member_unique_id'];
}
if ($stmt = $db->prepare("INSERT clients (client_id, member_unique_id, client_unique_id, client_key, client_first_name, client_last_name, client_organisation_name, client_business_type, client_username, client_address_line_1, client_address_line_2, client_town, client_county, client_postcode, client_telephone, client_mobile, client_email_address, client_password, client_additional_info) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
$stmt->bind_param("sssssssssssssssssss", $insertId, $member_unique_ids, $generatedId, $passKey[$key], $firstName[$key], $surname[$key], $businessName[$key], $accountType[$key], $userName[$key], $addressLine1[$key], $addressLine2[$key], $townCity[$key], $county[$key], $postcode[$key], $telephone[$key], $mobile[$key], $email[$key], $password, $additionalInfo[$key]);
$stmt->execute();
$stmt->close();
echo $db->insert_id;
} else {
echo "ERROR: Could not prepare Insert SQL statement.";
}
} else {
if ($stmt = $db->prepare("UPDATE clients SET client_first_name = ?, client_last_name = ?, client_organisation_name = ?, client_business_type = ?, client_username = ?, client_address_line_1 = ?, client_address_line_2 = ?, client_town = ?, client_county = ?, client_postcode = ?, client_telephone = ?, client_mobile = ?, client_email_address = ?, client_additional_info = ? WHERE client_id = ?")) {
$stmt->bind_param("ssssssssssssssi", $firstName[$key], $surname[$key], $businessName[$key], $accountType[$key], $userName[$key], $addressLine1[$key], $addressLine2[$key], $townCity[$key], $county[$key], $postcode[$key], $telephone[$key], $mobile[$key], $email[$key], $additionalInfo[$key], $client);
$stmt->execute();
$stmt->close();
echo $client;
} else {
echo "ERROR: Could not prepare Update SQL statement.";
}
}
}
<head>
<!--START-->
<?PHP include('../layout/start.php'); ?>
<!--/START-->
<script>
$(document).ready(function(){
function editClient(form) {
var $this = $(form);
var string = $this.serialize();
$.ajax({
type: "POST",
url: "../includes/db-edit-client.php",
data: string,
cache: false,
success: function(data){
setTimeout(function () {
window.location = "view-client.php?member=<?=$member_unique_id?>&client="+data;
}, 0);
}
});
}
$('body').on('click', '#updateClientDetails', function(e) {
editClient("#editClientForm");
});
});
</script>
</head>
<body>
<!--MAIN ELEMENTS-->
<?PHP include('../layout/header.php'); ?>
<?PHP include('../layout/menu.php'); ?>
<div class="pageWrapper shrink">
<div class="pageContainer">
<!--/MAIN ELEMENTS-->
<!--START FORM-->
<form id="editClientForm">
<input type="hidden" name="createClientId[]" value="<?=$_GET['client']?>">
<input type="hidden" name="PassKey[]">
<div class="titleBox clientBlue">
Edit Client - <?=$client_organisation_name?>
<button id="updateClientDetails" class="mainButton clientBlue">Update Client</button>
</div>
<div class="breadcrumbs">
<ul id="breadcrumbsList">
<li>Home</li>
<li>Clients</li>
<li>Edit Client - <?=$client_organisation_name?></li>
</ul>
</div>
<!--TABLE-->
<div class="tableContainer">
<div class="tableHeader clientBlue">
<div class="col12 colNoPaddingLeft">Client Details</div>
</div>
<div class="tableBody">
<div class="rowTight">
<div class="col3 colNoPaddingLeft"><input type="text" class="formInput" name="FirstName[]" placeholder="First name" autocomplete="off" value="<?=$client_first_name?>"></div>
<div class="col3"><input type="text" class="formInput" name="Surname[]" placeholder="Surname" autocomplete="off" value="<?=$client_last_name?>"></div>
<div class="col3"><input type="text" class="formInput" name="BusinessName[]" placeholder="Business name" autocomplete="off" value="<?=$client_organisation_name?>"></div>
<div class="col3 colNoPaddingRight"><input type="text" class="formInput" name="Username[]" placeholder="Username" autocomplete="off" value="<?=$client_username?>"></div>
</div>
</div>
</div><!--END TABLE-->
<!--TABLE-->
<div class="tableContainer">
<div class="tableHeader clientBlue">
<div class="col12 colNoPaddingLeft">Contact Details</div>
</div>
<div class="tableBody">
<div class="rowTight">
<div class="col3 colNoPaddingLeft"><input type="text" class="formInput" name="AddressLine1[]" placeholder="Address line 1" autocomplete="off" value="<?=$client_address_line_1?>"></div>
<div class="col3"><input type="text" class="formInput" name="AddressLine2[]" placeholder="Address line 2" autocomplete="off" value="<?=$client_address_line_2?>"></div>
<div class="col3"><input type="text" class="formInput" name="TownCity[]" placeholder="Town/city" autocomplete="off" value="<?=$client_town?>"></div>
<div class="col3 colNoPaddingRight"><input type="text" class="formInput" name="County[]" placeholder="County" autocomplete="off" value="<?=$client_county?>"></div>
</div>
<div class="rowTight">
<div class="col3 colNoPaddingLeft"><input type="text" class="formInput" name="Postcode[]" placeholder="Postcode" autocomplete="off" value="<?=$client_postcode?>"></div>
<div class="col3"><input type="text" class="formInput" name="Telephone[]" placeholder="Telephone" autocomplete="off" value="<?=$client_telephone?>"></div>
<div class="col3"><input type="text" class="formInput" name="Mobile[]" placeholder="Mobile" autocomplete="off" value="<?=$client_mobile?>"></div>
<div class="col3 colNoPaddingRight"> </div>
</div>
</div>
</div><!--END TABLE-->
<!--TABLE-->
<div class="tableContainer">
<div class="tableHeader clientBlue">
<div class="col12 colNoPaddingLeft">Account Details</div>
</div>
<div class="tableBody">
<div class="rowTight">
<div class="col3 colNoPaddingLeft">
<select name="AccountType[]" class="formDropdown">
<option value="Business type" selected>Business type</option>
<?php
$types = array('Landlord', 'Tenant', 'Letting agent', 'Estate agent', 'Surveyors', 'Insurance', 'Other');
foreach ($types as $type) {
$selected = $client_business_type == $type ? ' selected="selected"' : null;
echo '<option value="'.$type.'"'.$selected.'>'.$type.'</option>';
}
?>
</select>
</div>
<div class="col3"><input type="email" class="formInput" name="EmailAddress[]" placeholder="Email address" autocomplete="off" value="<?=$client_email_address?>"></div>
<div class="col3"><textarea placeholder="Additional information" name="AdditionalInformation[]" class="formInput"><?=$client_additional_info?></textarea></div>
<div class="col3 colNoPaddingRight"> </div>
</div>
</div>
</div><!--END TABLE-->
</form><!--END FORM-->
</div><!--END PAGE CONTAINER-->
</div><!--END PAGE WRAPPER-->
This is a project for school. I'm am trying to post to the database, but after I click on submit it comes back with an error about the line with bind_param:
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in /var/www/html/ticketsysteem/acties/nieuwTicket.php:42 Stack trace: #0 {main} thrown in /var/www/html/ticketsysteem/acties/nieuwTicket.php on line 42
Can somebody help me?
<?php
//var
$naam = trim($_POST["klantNaam"]);
$achternaam = trim($_POST["klantAchternaam"]);
$tel = trim($_POST["klantTel"]);
$adres = trim($_POST["klantAdres"]);
$postcode = trim($_POST["klantPostc"]);
$stad = trim($_POST["klantStad"]);
$email = trim($_POST["klantEmail"]);
//nieuwe klant
if (isset($_POST['submit1'])) {
$insertklant= $connectie->prepare("INSERT INTO klant klantAchternaam = $achternaam,
klantNaam = $naam, klantTel = $tel, klantAdres = $adres, klantPostc = $postcode,
klantStad = $stad, klantEmail = $email");
$insertklant->bind_param('sssssss', $achternaam, $naam, $tel, $adres, $postcode, $stad, $email);
if($insertklant->execute()) {
echo 'gelukt!';
}
}
?>
<form name="nieuwTicket" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<button onclick="nieuwek()" type="button" id="nk" >nieuwe klant </button>
<label class="hidden01">naam:</label><input id="text1" type="text" name="klantNaam" class="hidden"/><br>
<label class="hidden01">achternaam:</label><input id="text1" type="text" name="klantAchternaam" class="hidden"/><br>
<label class="hidden01">adres:</label><input id="text1" type="text" name="klantAdres" class="hidden"/><br>
<label class="hidden01">postcode:</label><input id="text1" type="text" name="klantPostc" class="hidden"/><br>
<label class="hidden01">woonplaats:</label><input id="text1" type="text" name="klantStad" class="hidden"/><br>
<label class="hidden01">telefoonnummer:</label><input id="text1" type="text" name="klantTel" class="hidden"/><br>
<input type="submit" name="submit1" value="invoeren" class="hidden">
</form>
Learn how to use prepared statements and what they actually do:
<?php
$stmt = $connectie->prepare("
INSERT INTO klant
klantAchternaam = ?,
klantNaam = ?,
klantTel = ?,
klantAdres = ?,
klantPostc = ?,
klantStad = ?,
klantEmail = ?
");
if($stmt){
$stmt->bind_param('sssssss', $achternaam, $naam, $tel, $adres, $postcode, $stad, $email);
if($stmt->execute()) {
echo 'gelukt!';
}
}
?>
Your current code is wide open to sql injection, while the above code is fully secured against them. The whole idea of prepared statements is that you never have to concat user submitted values directly to the sql query.
The following code is created to register a user in my website. When I try to register a user the 'query' is being executed but the new record in the database is not shown.
The following code is the register form:
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="page-header">
<h2>Register Now</h2>
</div>
<div>
<form id="defaultForm" method="post" name="registerform" class="form-horizontal" action="index.php">
<div class="form-group">
<div class="col-lg-11">
<?php include('include/showErrors.php'); ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="username" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email address</label>
<div class="col-lg-5">
<input type="email" class="form-control" name="email" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Password</label>
<div class="col-lg-5">
<input type="password" class="form-control" name="password" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Age</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="age" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Sex</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="sex" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Country</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="country" autocomplete="off" />
</div>
</div>
<div class="form-group">
<div class="col-lg-8 col-lg-offset-3">
<button name="Submit" type="submit" class="btn btn-primary">Sign up</button>
</div>
</div>
<br>
</form>
</div>
</div>
The following is the doRegister user:
class Registration
{
private $dbCon = null;
public $regSuccessful = false;
public $verificationSuccess = false;
public $errors = array();
public $messages = array();
//the below function will automaticcaly start when a obejct of this class is created
public function __construct()
{
//session_start();
if(isset($_POST["Submit"]))
{
$this->registerUser($_POST['username'], $_POST['password'],$_POST['email'],$_POST['age'],$_POST['sex'],$_POST['country']);
}
else if (isset($_GET["id"]) && isset ($_GET["verification_code"]))
{
$this->verifyUser($_GET["id"], $_GET["verification_code"]);
}
}
//the following methods checks if a database connection is open or not
private function dbConnection()
{
if($this->dbCon != null)
{
return true;
}
else
{
//create database connection
try
{
$this->dbCon = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
return true;
} catch (PDOException $ex) {
$this->errors[] = MESSAGE_DATABASE_ERROR;
return false;
}
}
}
//the following method will handle and the registration errors
private function registerUser($username,$password,$email,$age, $sex,$country)
{
//this will remove extra spaces
$username = trim($username);
$email = trim($email);
$sex = trim($sex);
$country = trim($country);
if(empty($username))
{
$this->errors[] = MESSAGE_USERNAME_EMPTY;
}
else if(empty($password))
{
$this->errors[] = MESSAGE_PASSWORD_EMPTY;
}
else if(empty($country))
{
$this->errors[] = MESSAGE_COUNTRY_EMPTY;
}
else if(empty($sex))
{
$this->errors[] = MESSAGE_SEX_EMPTY;
}
else if(empty($age))
{
$this->errors[] = MESSAGE_AGE_EMPTY;
}
else if(strlen($password) < 6)
{
$this->errors[] = MESSAGE_PASSWORD_TOO_SHORT;
}
elseif (strlen($username) > 64 || strlen($username) < 2)
{
$this->errors[] = MESSAGE_USERNAME_BAD_LENGTH;
}
elseif (!preg_match('/^[a-z\d]{2,64}$/i', $username)) {
$this->errors[] = MESSAGE_USERNAME_INVALID;
} elseif (!preg_match('/^[a-z\d]{2,64}$/i', $country)) {
$this->errors[] = MESSAGE_COUNTRY_INVALID;
}
elseif (!preg_match('/^[a-z\d]{2,64}$/i', $sex)) {
$this->errors[] = MESSAGE_SEX_INVALID;
}
elseif (empty($email)) {
$this->errors[] = MESSAGE_EMAIL_EMPTY;
} elseif (strlen($email) > 64) {
$this->errors[] = MESSAGE_EMAIL_TOO_LONG;
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->errors[] = MESSAGE_EMAIL_INVALID;
}else if ($this->dbConnection())
{
// check if username or email already exists
$check_user_name = $this->dbCon->prepare('SELECT username, email FROM tbl_users WHERE username=:username OR email=:email');
$check_user_name->bindValue(':username', $username, PDO::PARAM_STR);
$check_user_name->bindValue(':email', $email, PDO::PARAM_STR);
$check_user_name->execute();
$result = $check_user_name->fetchAll();
// if username or/and email find in the database
// TODO: this is really awful!
if (count($result) > 0) {
for ($i = 0; $i < count($result); $i++) {
$this->errors[] = ($result[$i]['username'] == $username) ? MESSAGE_USERNAME_EXISTS : MESSAGE_EMAIL_ALREADY_EXISTS;
}
} else {
// check if we have a constant HASH_COST_FACTOR defined (in config/hashing.php),
// if so: put the value into $hash_cost_factor, if not, make $hash_cost_factor = null
//$hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
//the following will encrypt users password with the PHP 5.5's hash function
//$userPassHash = password_hash($password, PASSWORD_BCRYPT);
// $userPassHash = password_hash( $password, PASSWORD_BCRYPT, array(
// 'cost' => 12
// ));
//this will generate a random hash for email verification
$user_activation_hash = sha1(uniqid(mt_rand()), true);
//the following will write a new user data into the database
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now()), :age, :sex, :country');
$queryUserInsert->bindValue(':username', $username, PDO::PARAM_STR);
$queryUserInsert->bindValue(':userPassHash', $password, PDO::PARAM_STR);
$queryUserInsert->bindValue(':email', $email, PDO::PARAM_STR);
$queryUserInsert->bindValue(':user_activation_hash', $user_activation_hash, PDO::PARAM_STR);
$queryUserInsert->bindValue(':user_registration_ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$queryUserInsert->bindValue(':age', $age, PDO::PARAM_STR);
$queryUserInsert->bindValue(':sex', $sex, PDO::PARAM_STR);
$queryUserInsert->bindValue(':country', $country, PDO::PARAM_STR);
$queryUserInsert->execute();
//id of the new user registered
//$user_id = $this->dbCon->lastInsertId();
//checks if the query was succesfull, and send verification email
if($queryUserInsert)
{
$this->messages[] = MESSAGE_REGISTRATION_ACTIVATION_SUCCESSFUL;
}
else
{
$this->errors[] = MESSAGE_REGISTRATION_FAILED;
}
}
}
}
}
Screenshot of the Database:
Use this insert query:
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now(), :age, :sex, :country)');
You have added an extra ) after now() function in query; Put it after :country
Change
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now()), :age, :sex, :country');
^ Extra Closing Bracket ^ Closing Bracket For VALUES missing
To
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now(), :age, :sex, :country)');
Extra closing bracket in now()
Didn't closed bracket for VALUES.
Hi all I'm looking for some guidance as to how can I build a php form which includes both text and an image uploader. I am able to do the two forms separately but am having a bit of difficulty in joining things together.
My html form:
<form name="news-page" action="" method="POST" enctype="multipart/form-data">
<h1>News</h1>
<span id="newstitle">
<p id="newstitle">News Title</p>
<input id="title" type="text" name="newstitle" value="News Title"/>
</span>
<span id="newsdate">
<p>News Date</p>
<input id="news_date" type="text" name="newsdate" value="News Date"/>
</span>
<span id="category">
<p>News Category</p>
<input id="newscategory" type="text" name="newscategory" value="News Category"/>
</span>
<p id="news_info">News Information</p>
<textarea id="newsinfo" name="newstext">Bacon ipsum dolor amet turducken boudin sirloin ..</textarea>
<div id="newsimage">
<img src/>
<p>Insert News Image</p>
<label class="myLabel" id="news-image-upload">
<input type="file" required name="newsuploader" id="fileToUpload" />
<span>Select Image</span>
</label>
<button type="submit" name="add_news_btn">Add News</button>
</div>
</form>
Code to insert text
if (isset($_POST['add_news_btn'])) {
$newsdate = (isset($_POST['newsdate']) ? $_POST['newsdate'] : null);
$newstitle = (isset($_POST['newstitle']) ? $_POST['newstitle'] : null);
$newscatagory = (isset($_POST['newscategory']) ? $_POST['newscategory'] : null);
$newstext = (isset($_POST['newstext']) ? $_POST['newstext'] : null);
include 'connect.php';
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory) VALUES(?, ?, ?, ?)");
$stmt->bind_param('ssss', $newsdate, $newstitle, $newstext, $newscatagory);
$stmt->execute();
$stmt->close();
echo "done";
}
code to upload image
if (isset($_FILES['newsuploader'])) {
if ($_FILES["newsuploader"]["error"] > 0) {
echo "No file chosen</br>";
echo "Database fail</br>";
}
else {
move_uploaded_file($_FILES["newsuploader"]["tmp_name"], "../media/images/" . $_FILES["newsuploader"]["name"]);
echo "Saved";
$file = "media/images/" . $_FILES["newsuploader"]["name"];
include 'connect.php';
if (!mysqli_select_db($conn, "mostacms_db")) {
echo "Error: " . mysql_error();
}
else echo "all good";
}
$stmt = $conn->prepare("INSERT INTO news(imageURL) VALUES(?)");
$stmt->bind_param('s', $file);
$stmt->execute();
$conn->close();
}
Try posting into this php file.
if (isset($_POST['add_news_btn'])) {
include 'connect.php';
$newsdate = (isset($_POST['newsdate']) ? $_POST['newsdate'] : null);
$newstitle = (isset($_POST['newstitle']) ? $_POST['newstitle'] : null);
$newscatagory = (isset($_POST['newscategory']) ? $_POST['newscategory'] : null);
$newstext = (isset($_POST['newstext']) ? $_POST['newstext'] : null);
// upload file
if (isset($_FILES['newsuploader'])) {
if(move_uploaded_file($_FILES["newsuploader"]["tmp_name"], "../media/images/" . $_FILES["newsuploader"]["name"]))
echo "Saved";
$imageURL = "media/images/" . $_FILES["newsuploader"]["name"];
}
else
$imageURL='';
// update details to DB
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory,imageURL ) VALUES(?, ?, ?, ?,?)");
$stmt->bind_param('sssss', $newsdate, $newstitle, $newstext, $newscatagory, $imageURL);
$stmt->execute();
$stmt->close();
}
Note: To avoid duplicate file insertion try changing the filename to something unique before saving it.
try to change this statement
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory) VALUES(?, ?, ?, ?)");
$stmt->bind_param('ssss', $newsdate, $newstitle, $newstext, $newscatagory);
to
$stmt = $conn->prepare("INSERT INTO news (date, title, content, newscatagory) VALUES(?, ?, ?, ?,?)");
$stmt->bind_param('sssss', $newsdate, $newstitle, $newstext, $newscatagory,$file);