When I submit my data from the form, it won't insert the form data in to the database. The connection to the databse is set and when I check the connection it always responds that it is connected. The database is correctly setup with all values: id, name, date, emailadress and text. The username, password and database name are correct.
The syntax should be correct. I work with mysql workbench.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<title></title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="input.css">
<header>
<h1></h1>
</header>
<nav>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</nav>
<main>
<form method="post" action="input.php">
<label>Name</label>
<input placeholder="Name" name="name" type="text"><br>
<label>Mailadress</label>
<input placeholder="Emailadress" name="eMail" type="email"><br>
<label>Your comment</label>
<textarea name="comment" placeholder="Text" name="comment"cols="60" rows="15"></textarea>
<input value="Send" type="submit">
</form>
</main>
</body>
</html>
PHP code:
<?php
if($con->connect_error)
{
die("No connection" .$con-> connect_error);
}
echo "Connected";
$guestbook = new GuestbookAccess();
if (isset($_POST['submit'])){
$name = $_POST['name']; $eMail = $_POST['eMail']; $comment = $_POST['comment'];
}
class GuestbookAccess
{
private $db;
/**
* Opens the database.
*/
public function __construct()
{
$username = "tipuser";
$password = "TIP2018_WebEngineering";
$database = "tip";
// Open the database
$this->db = mysqli_connect("localhost", $username, $password);
if ($this->db == false) {
die("Unable to connect to database");
}
// Select database
mysqli_select_db($this->db, $database);
}
/**
* Evaluates current time and adds a new guestbook entry with given name,
* e-Mail and comment.
* #param String $name User name
* #param String $eMail User e-mail address
* #param String $comment The entry text
* #return On success: Integer Index generated by the database for the entry
* On failure: Boolean false
*/
public function addEntry($name, $eMail, $comment)
{
// For security: suppress SQL injection
$name = mysqli_real_escape_string($this->db, $name);
$eMail = mysqli_real_escape_string($this->db, $eMail);
$comment = mysqli_real_escape_string($this->db, $comment);
// Add entry to the database
$result = mysqli_query($this->db, "INSERT INTO guestbook (name, email, comment) VALUES ('$name', '$eMail', '$comment')");
if ($result)
{
$result = mysqli_insert_id($this->db);
}
return $result;
}
/**
* Return in an table (two-dimensional array) all entries of the guest book.
* Each row of the table represents one entry in the guest book.
* #return table[...]["Index"] --> Integer: Index of the entry (for deleting)
* table[...]["Name"] --> String: name of the user
* table[...]["eMail"] --> String: e-Mail of the user
* table[...]["Comment"] --> String: The guest book entry (as text)
* table[...]["Date"] --> String: Date and time of the entry
*/
public function getEntries()
{
// Create query
$result = mysqli_query($this->db, "SELECT * FROM guestbook");
$table = false;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$table[$i]["Index"] = $row["indes"];
$table[$i]["Date"] = $row["date"];
$table[$i]["Name"] = $row["name"];
$table[$i]["eMail"] = $row["email"];
$table[$i]["Comment"] = $row["comment"];
$i++;
}
mysqli_free_result($result);
return $table;
// Get all entries in the guestbook
$table = $guestbook->getEntries();
if ($table) { // Check if there are enrtries
echo "\nThe guestbook contains:\n";
foreach ($table as $row) {
// Output each element
$index = $row["Index"];
$name = $row["Name"];
$date = $row["Date"];
$email = $row["eMail"];
$comment = $row["Comment"];
echo "Index: $index, ";
echo "Name: $name, ";
echo "Date: $date, ";
echo "eMail: $email, ";
echo "Comment: $comment\n";
}
}
else {
echo "\nGuest book is empty\n";
}
/**
* Closes the database.
*/
function __destruct()
{
mysqli_close($this->db);
}
}
}
?>
You should add name as submit for submit type in your input tage so to make the isset($_POST['submit']) work in php
<input value="Send" type="submit" name="submit">
Related
I'm new at PHP and I've been following a course on how to make a sign up/login page. I have successfully finished the signup page but the login page is giving me issues. Here is my code for my login.php:
<?php
include_once '../resources/session.php';
include_once '../resources/database.php';
include_once '../resources/utilities.php';
if(isset($_POST['loginBtn'])){
// array to hold errors
$form_errors = array();
// validate
$required_fields = array('username ', 'password ');
$form_errors = array_merge($form_errors, check_empty_fields($required_fields));
if(empty($form_errors)){
// collect form data
$user = $_POST['username'];
$password = $_POST['password'];
// check if user exists in the database
$sqlQuery = "SELECT * FROM users WHERE username = :username";
$statement = $db->prepare($sqlQuery);
$statement->execute(array(':username' => $user));
while($row = $statement->fetch()){
$id = $row['id'];
$hashedpassword = $row['password'];
$username = $row['username'];
if(password_verify($password, $hashed_password)){
$_SESSION['id'] = $id;
$_SESSION['username'] = $username;
header("location: dashboard.php");
}
else{
$result ="<p style='padding: 20px; color: red; border: 1px solid gray;'> Invalid username or password</p>";
}
}
}
else{
if(count($form_errors) == 1){
$result = "<p style='color:red;'>There was 1 error in the form</p>";
}
else{
$result = "<p style='color:red;'> There were " .count($form_errors). " errors in the form </p>";
}
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="../css/indexstyles.css">
</head>
<body>
<h2>Login Form</h2>
<?php if(isset($result)) echo $result; ?>
<?php if(!empty($form_errors)) echo show_errors($form_errors); ?>
<form action="" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" value="" name="username "></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" value="" name="password "></td>
</tr>
<tr>
<td></td>
<td><input style="float: right;" = type="submit" name="loginBtn" value="Login"></td>
</tr>
</table>
</form>
</html>
My code for database.php is:
<?php
// intialize variables to hold connection parameters
$username = 'root';
$dsn = 'mysql:host=localhost; dbname=register';
$password = 'xxxx';
try{
// create an instance of the PDO class with the required parameters
$db = new PDO($dsn, $username, $password);
// set PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// display success message
// echo "Connected to the register database";
}catch (PDOException $ex){
// display error message
echo "Connection unsuccesful. ERROR: ".$ex->getMessage();
}
and my code for utilities.php is this:
<?php
/**
* #param $required_fields_array, n array containing the list of all required fields
* #return array, containing all errors
*/
// start
function check_empty_fields($required_fields_array){
// initialize an array to store error messages
$form_errors = array();
// loop throgh the required fields array and popular the form error array
foreach ($required_fields_array as $name_of_field){
if(!isset($_POST[$name_of_field]) || $_POST[$name_of_field] == NULL){
$form_errors[] = $name_of_field . "is a required field";
}
}
return $form_errors;
}
/**
* #param $fields_to_check_length, an array containing the name of fields
* for which we wnt th check min required length e.g. array('username' => 4, 'email' => 12)
* #return array, containing all errors
*/
function check_min_length($fields_to_check_length){
//initialize an array to store error messages
$form_errors = array();
foreach($fields_to_check_length as $name_of_field => $minimum_length_required){
if(strlen(trim($_POST[$name_of_field])) < $minimum_lenth_required){
$form_errors[] = $name_of_field . " is too short, must be {$minimum_length_required} characters long";
}
}
return $form_errors;
}
/**
* #param $data, store a key/value pair array where key is the name of the form control
* in this case 'email' and value is the input entered by the user
* #return array, containing email error
*/
function check_email($data){
//initialize an array to store error messages
$form_errors + array();
$key = 'email';
// check if the key email exists in data array
if(array_key_exists($key, $data)){
// check if the email field has a value
if($_POST[$key] != null){
// remove all illegal characters from email
$key = filter_var($key, FILTER_SANITIZE_EMAIL);
// check if input is a valid email addresss
if(filter_var($_POST[$key], FILTER_VALIDATE_EMAIL) === false){
$form_errors[] = $key . " is not a valid email address";
}
}
}
return $form_errors;
}
/**
* #param $form_errors_array, the array holding all
* errors which we want to loop through
* #return string, list containing all error messages
*/
function show_errors($form_errors_array){
$errors = "<p><ul style ='color: red;'>";
// loop through error array and display all items in a list
foreach($form_errors_array as $the_error){
$errors .= "<li> {$the_error} </li>";
}
$errors .= "</ul><p>";
return $errors;
}
Lastly, my sessions.php is:
<?php
session_start();
When I press the login button without entering anything, I get the expected error message. However, if I enter the demo account I made, I still get the same error message.
Any help is greatly appreciated!
Sianna
A
The fields you are checking as required contain spaces at the end:
$required_fields = array('username ', 'password ');
So therefore these names never exist in the posted data. Change that line to:
$required_fields = array('username', 'password');
And it should work.
UPDATE: I didn't notice before but your form inputs also have the space at the end of the name. Remove the space from there too. When the form is submitted and has those spaces at the end the $_POST contains 'username_' and 'password_'. i.e. PHP is converting the spaces to underscores.
If you added the space just so that the error message had a space then the correct place to add the space would be just before "is a required field" and not in the input names themselves.
Remember to reload the page after making that change.
So i have the following scripts:
<?php
//Posts variables
$post_id = 0;
$isEditingPost = false;
$published = 0;
$title = "";
$post_slug = "";
$body = "";
$featured_image = "";
$post_topic = "";
//Get all posts
function getAllPosts(){
global $conn;
if ($_SESSION['user']['role'] == "Admin") {
$sql = "SELECT * FROM posts";
}elseif($_SESSION['user']['role'] == "Author"){
$user_id = $_SESSION['user']['id'];
$sql = "SELECT * FROM posts WHERE user_id=$user_id";
}
$result = mysqli_query($conn,$sql);
$posts = mysqli_fetch_all($result,MYSQLI_ASSOC);
$final_posts = array();
foreach($posts as $post){
$post['author'] = getPostAuthorById($post['user_id']);
array_push($final_posts,$post);
}
return $final_posts;
}
function getPostAuthorById($user_id){
global $conn;
$sql = "SELECT username FROM users WHERE id=$user_id";
$result = mysqli_query($conn,$sql);
if($result){
return mysqli_fetch_assoc($result)['username'];
}else{
return null;
}
}
/* - - - - - - - - - -
- Post actions
- - - - - - - - - - -*/
// if user clicks the create post button
if (isset($_POST['create_post'])) { createPost($_POST); }
// if user clicks the Edit post button
if (isset($_GET['edit-post'])) {
$isEditingPost = true;
$post_id = $_GET['edit-post'];
editPost($post_id);
}
// if user clicks the update post button
if (isset($_POST['update_post'])) {
updatePost($_POST);
}
// if user clicks the Delete post button
if (isset($_GET['delete-post'])) {
$post_id = $_GET['delete-post'];
deletePost($post_id);
}
/* - - - - - - - - - -
- Post functions
- - - - - - - - - - -*/
function createPost($request_values)
{
global $conn,$user_id, $errors, $title, $featured_image, $topic_id, $body, $published;
$user_id = $_SESSION['user']['id'];
$title = esc($request_values['title']);
$body = htmlentities(esc($request_values['body']));
if (isset($request_values['topic_id'])) {
$topic_id = esc($request_values['topic_id']);
}
if (isset($request_values['publish'])) {
$published = esc($request_values['publish']);
}
// create slug: if title is "The Storm Is Over", return "the-storm-is-over" as slug
$post_slug = makeSlug($title);
// validate form
if (empty($title)) { array_push($errors, "Post title is required"); }
if (empty($body)) { array_push($errors, "Post body is required"); }
if (empty($topic_id)) { array_push($errors, "Post topic is required"); }
// Get image name
$featured_image = $_FILES['featured_image']['name'];
if (empty($featured_image)) { array_push($errors, "Featured image is required"); }
// image file directory
$target = "../static/images/" . basename($featured_image);
if (!move_uploaded_file($_FILES['featured_image']['tmp_name'], $target)) {
array_push($errors, "Failed to upload image. Please check file settings for your server");
}
// Ensure that no post is saved twice.
$post_check_query = "SELECT * FROM posts WHERE slug='$post_slug' LIMIT 1";
$result = mysqli_query($conn, $post_check_query);
if (mysqli_num_rows($result) > 0) { // if post exists
array_push($errors, "A post already exists with that title.");
}
// create post if there are no errors in the form
if (count($errors) == 0) {
$query = "INSERT INTO posts (user_id, title, slug, image, body, published, created_at, updated_at) VALUES($user_id, '$title', '$post_slug', '$featured_image', '$body', $published, now(), now())";
if(mysqli_query($conn, $query)){ // if post created successfully
$inserted_post_id = mysqli_insert_id($conn);
// create relationship between post and topic
$sql = "INSERT INTO post_topic (post_id, topic_id) VALUES($inserted_post_id, $topic_id)";
mysqli_query($conn, $sql);
$_SESSION['message'] = "Post created successfully";
header('location: posts.php');
exit(0);
}
}
}
/* * * * * * * * * * * * * * * * * * * * *
* - Takes post id as parameter
* - Fetches the post from database
* - sets post fields on form for editing
* * * * * * * * * * * * * * * * * * * * * */
function editPost($role_id)
{
global $conn, $title, $post_slug, $body, $published, $isEditingPost, $post_id;
$sql = "SELECT * FROM posts WHERE id=$role_id LIMIT 1";
$result = mysqli_query($conn, $sql);
$post = mysqli_fetch_assoc($result);
// set form values on the form to be updated
$title = $post['title'];
$body = $post['body'];
$published = $post['published'];
}
function updatePost($request_values)
{
global $conn, $errors, $post_id, $title, $featured_image, $topic_id, $body, $published;
$title = esc($request_values['title']);
$body = esc($request_values['body']);
$post_id = esc($request_values['post_id']);
if (isset($request_values['topic_id'])) {
$topic_id = esc($request_values['topic_id']);
}
// create slug: if title is "The Storm Is Over", return "the-storm-is-over" as slug
$post_slug = makeSlug($title);
if (empty($title)) { array_push($errors, "Post title is required"); }
if (empty($body)) { array_push($errors, "Post body is required"); }
// if new featured image has been provided
if (isset($_POST['featured_image'])) {
// Get image name
$featured_image = $_FILES['featured_image']['name'];
// image file directory
$target = "../static/images/" . basename($featured_image);
if (!move_uploaded_file($_FILES['featured_image']['tmp_name'], $target)) {
array_push($errors, "Failed to upload image. Please check file settings for your server");
}
}
// register topic if there are no errors in the form
if (count($errors) == 0) {
$query = "UPDATE posts SET title='$title', slug='$post_slug', views=0, image='$featured_image', body='$body', published=$published, updated_at=now() WHERE id=$post_id";
// attach topic to post on post_topic table
if(mysqli_query($conn, $query)){ // if post created successfully
if (isset($topic_id)) {
$inserted_post_id = mysqli_insert_id($conn);
// create relationship between post and topic
$sql = "INSERT INTO post_topic (post_id, topic_id) VALUES($inserted_post_id, $topic_id)";
mysqli_query($conn, $sql);
$_SESSION['message'] = "Post created successfully";
header('location: posts.php');
exit(0);
}
}
$_SESSION['message'] = "Post updated successfully";
header('location: posts.php');
exit(0);
}
}
// delete blog post
function deletePost($post_id)
{
global $conn;
$sql = "DELETE FROM posts WHERE id=$post_id";
if (mysqli_query($conn, $sql)) {
$_SESSION['message'] = "Post successfully deleted";
header("location: posts.php");
exit(0);
}
}
// if user clicks the publish post button
if (isset($_GET['publish']) || isset($_GET['unpublish'])) {
$message = "";
if (isset($_GET['publish'])) {
$message = "Post published successfully";
$post_id = $_GET['publish'];
} else if (isset($_GET['unpublish'])) {
$message = "Post successfully unpublished";
$post_id = $_GET['unpublish'];
}
togglePublishPost($post_id, $message);
}
// delete blog post
function togglePublishPost($post_id, $message)
{
global $conn;
$sql = "UPDATE posts SET published=!published WHERE id=$post_id";
if (mysqli_query($conn, $sql)) {
$_SESSION['message'] = $message;
header("location: posts.php");
exit(0);
}
}
?>
Everything works fine , it updates the topic , the post body,title,published state but the image isn't updating , even tho when i create a new post the image is being inserted in the database , when i try to update , the image column in database remains empty.
Here is the create_post.php
<?php include('../config.php'); ?>
<?php include(ROOT_PATH . '/admin/includes/admin_functions.php'); ?>
<?php include(ROOT_PATH . '/admin/includes/post_functions.php'); ?>
<?php include(ROOT_PATH . '/admin/includes/header.php'); ?>
<!-- Get all topics -->
<?php $topics = getAllTopics(); ?>
<title>Admin | Create Post</title>
</head>
<body>
<!-- admin navbar -->
<?php include(ROOT_PATH . '/admin/includes/navbar.php') ?>
<div class="container content">
<!-- Left side menu -->
<?php include(ROOT_PATH . '/admin/includes/menu.php') ?>
<!-- Middle form - to create and edit -->
<div class="action create-post-div">
<h1 class="page-title">Create/Edit Post</h1>
<form method="post" enctype="multipart/form-data" action="<?php echo BASE_URL . 'admin/create_post.php'?>">
<?php include(ROOT_PATH . '/includes/errors.php') ?>
<?php if($isEditingPost == true):?>
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
<?php endif ?>
<input type="text" name="title" value="<?php echo $title; ?>" placeholder="Title">
<label style="float: left; margin: 5px auto 5px;">Featured image</label>
<input type="file" name="featured_image">
<textarea name="body" id="body" cols="30" rows="10"><?php echo $body; ?></textarea>
<select name="topic_id">
<option value="" selected disabled>Choose topic</option>
<?php foreach ($topics as $topic): ?>
<option value="<?php echo $topic['id']; ?>">
<?php echo $topic['name']; ?>
</option>
<?php endforeach ?>
</select>
<?php if($_SESSION['user']['role'] == 'Admin'):?>
<?php if($published == true):?>
<label for="publish">
Publish
<input type="checkbox" value='1' name="publish" checked="checked">
</label>
<?php else:?>
<label for="publish">
Publish
<input type="checkbox" value="1" name="publish">
</label>
<?php endif ?>
<?php endif ?>
<?php if ($isEditingPost === true): ?>
<button type="submit" class="btn" name="update_post">UPDATE</button>
<?php else: ?>
<button type="submit" class="btn" name="create_post">Save Post</button>
<?php endif ?>
</form>
</div>
</body>
</html>
<script>
CKEDITOR.replace('body');
</script>
I think the problem might be with your if statement in updatePost function if (isset($_POST['featured_image'])) {. Change this like in createPost function
$featured_image = $_FILES['featured_image']['name'];
if (empty($featured_image)) {
...
}
Check also https://www.php.net/manual/en/features.file-upload.post-method.php for more information about checking uploaded files.
$_POST is not getting any values and i have tried a lot of procedure already mentioned on stack overflow but they are not working for me. I have tried printing the $_POST it is empty. i need some suggestions on it..please help
It was previously working when it was in mysql database but i tried to change the database to sqlserver and now its not working but i am not understanding i have not made any changes to this particular code and i have seen this also that it is not being affected by some other file.
there is no mistake in empty condition i wrote it myself to check whether it was empty or not and it was always showing empty whether i submit data or not
i am attaching some codes which are related to this.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<?php
ob_start();
session_start();
require_once 'config.php';
?>
<?php
if(empty($_POST)){
echo "hello";
try {
$user_obj = new Cl_User();
$data = $user_obj->registration( $_POST );
if($data){
$_SESSION['success'] = USER_REGISTRATION_SUCCESS;
header('Location: index.php');exit;
}
} catch (Exception $e) {
$_SESSION['error'] = $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="php quiz script, php quiz code, php quiz application, quiz php code, php quiz system, online quiz using php, quiz using php, how to make quiz in php, quiz system in php, php programming quiz, online quiz using php and sqlsrv, create online quiz using php and sqlsrv, create quiz using php sqlsrv, php quiz script free">
<meta name="keywords" content="php quiz script, php quiz code, php quiz application, quiz php code, php quiz system, online quiz using php, quiz using php, how to make quiz in php, quiz system in php, php programming quiz, online quiz using php and sqlsrv, create online quiz using php and sqlsrv, create quiz using php sqlsrv, php quiz script free">
<title>PHP Quiz Script</title>
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">PHP Quiz Application</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-register" role="form" id="register-form">
<div>
<input name="name" id="name" type="text" class="form-control" placeholder="Name">
<span class="help-block"></span>
</div>
<div>
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" >
<span class="help-block"></span>
</div>
<div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<span class="help-block"></span>
</div>
<div>
<input name="confirm_password" id="confirm_password" type="password" class="form-control" placeholder="Confirm Password">
<span class="help-block"></span>
</div>
<button class="btn btn-block bt-login" type="submit" id="submit" name="submit">Sign Up</button>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign In
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/register.js"></script>
</body>
</html>
<?php unset($_SESSION['success'] ); unset($_SESSION['error']); ?>
<?php
$server="NIKUNJ";
$ci = array("Database" => "My database","UID"=>"sa", "PWD"=>"sql#123","Characterset"=>"UTF-8") or die( "check db connect1" );
$conn = sqlsrv_connect($server,$ci) or die ( "check db connect2" ) ;
function mssql_escape($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
function mssql_insert_id() {
$id = 0;
$res = sqlsrv_query("SELECT ##identity AS id");
if ($row = sqlsrv_fetch_array($res, MSSQL_ASSOC)) {
$id = $row["id"];
}
return $id;
}
class Cl_User
{
/**
* #var will going contain database connection
*/
protected $_con;
/**
* it will initalize DBclass
*/
public function __construct()
{
$db = new Cl_DBclass();
$this->_con = $db->con;
}
/**
* this will handles user registration process
* #param array $data
* #return boolean true or false based success
*/
public function registration( array $data )
{
echo "hello";
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$name = mssql_escape( $trimmed_data['name'] );
$password = mssql_escape( $trimmed_data['password'] );
$cpassword = mssql_escape( $trimmed_data['confirm_password'] );
// Check for an email address:
if (filter_var( $trimmed_data['email'], FILTER_VALIDATE_EMAIL)) {
$email = mssql_escape( $trimmed_data['email']);
} else {
throw new Exception( "Please enter a valid email address!" );
}
if((!$name) || (!$email) || (!$password) || (!$cpassword) ) {
throw new Exception( FIELDS_MISSING );
}
if ($password !== $cpassword) {
throw new Exception( PASSWORD_NOT_MATCH );
}
$password = md5( $password );
$query = "INSERT INTO users (id, name, email, password, created) VALUES (NULL, '$name', '$email', '$password', CURRENT_TIMESTAMP)";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
return true;
};
} else{
throw new Exception( USER_REGISTRATION_FAIL );
}
}
/**
* This method will handle user login process
* #param array $data
* #return boolean true or false based on success or failure
*/
public function login( array $data )
{
$_SESSION['logged_in'] = false;
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$email = mssql_escape( $this->_con, $trimmed_data['email'] );
$password = mssql_escape( $this->_con, $trimmed_data['password'] );
if((!$email) || (!$password) ) {
throw new Exception( LOGIN_FIELDS_MISSING );
}
$password = md5( $password );
$query = "SELECT id, name, email, created FROM users where email = '$email' and password = '$password' ";
$result = sqlsrv_query($this->_con, $query);
$data = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC);
$count = SQLSRV_num_rows($result);
echo $count;
sqlsrv_close($this->_con);
if( $count == 1){
$_SESSION = $data;
$_SESSION['logged_in'] = true;
return true;
}else{
throw new Exception( LOGIN_FAIL );
}
} else{
throw new Exception( LOGIN_FIELDS_MISSING );
}
}
/**
* This will shows account information and handles password change
* #param array $data
* #throws Exception
* #return boolean
*/
public function account( array $data )
{
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$password = mssql_escape( $this->_con, $trimmed_data['password'] );
$cpassword = $trimmed_data['confirm_password'];
$user_id = $_SESSION['id'];
if((!$password) || (!$cpassword) ) {
throw new Exception( FIELDS_MISSING );
}
if ($password !== $cpassword) {
throw new Exception( PASSWORD_NOT_MATCH );
}
$password = md5( $password );
$query = "UPDATE users SET password = '$password' WHERE id = '$user_id'";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
return true;
}
} else{
throw new Exception( FIELDS_MISSING );
}
}
/**
* This handle sign out process
*/
public function logout()
{
session_unset();
session_destroy();
session_start();
$_SESSION['success'] = LOGOUT_SUCCESS;
header('Location: index.php');
}
/**
* This reset the current password and send new password to mail
* #param array $data
* #throws Exception
* #return boolean
*/
public function forgetPassword( array $data )
{
if( !empty( $data ) ){
// escape variables for security
$email = mssql_escape( $this->_con, trim( $data['email'] ) );
if((!$email) ) {
throw new Exception( FIELDS_MISSING );
}
$password = $this->randomPassword();
$password1 = md5( $password );
$query = "UPDATE users SET password = '$password1' WHERE email = '$email'";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
$to = $email;
$subject = "New Password Request";
$txt = "Your New Password ".$password;
$headers = "From: rahul.ranjan72#hotmail.com" . "\r\n" .
"CC:rahul.ranjan72#hotmail.com";
mail($to,$subject,$txt,$headers);
return true;
}
} else{
throw new Exception( FIELDS_MISSING );
}
}
/**
* This will generate random password
* #return string
*/
private function randomPassword()
{
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
public function pr($data = '' )
{
echo "<pre>"; print_r($data); echo "</pre>";
}
public function getCategory()
{
$query = "SELECT * FROM categories";
$results = sqlsrv_query($conn, $query) or die(SQLSRV_errors());
$categories = array();
while ( $result = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC) ) {
echo $result['id'];
$categories[$result['id']] = $result['category_name'];
}
return $categories;
}
public function getQuestions(array $data)
{
if( !empty( $data ) ){
// escape variables for security
$category_id = mssql_escape( $this->_con, trim( $data['category'] ) );
if((!$category_id) ) {
throw new Exception( FIELDS_MISSING );
}
$user_id = $_SESSION['id'];
$query = "INSERT INTO scores ( user_id,right_answer,category_id)VALUES ( '$user_id',0,'$category_id')";
sqlsrv_query( $this->_con, $query);
$_SESSION['score_id'] = mssql_insert_id();
$results = array();
$number_question = $_POST['num_questions'];
$total_question = $_POST['total_num_questions'];
$row = sqlsrv_query( $this->_con, "select * from questions where category_id=$category_id ORDER BY RAND()");
$check=SQLSRV_num_rows($row);
if($check<$total_question)
$rowcount=$check;
else
$rowcount = $total_question;
$remainder = $rowcount/$number_question;
$results['number_question'] = $number_question;
$results['remainder'] = $remainder;
$results['rowcount'] = $rowcount;
while ( $result = SQLSRV_FETCH_ASSOC($row) ) {
$results['questions'][] = $result;
}
sqlsrv_close($this->_con);
return $results;
} else{
throw new Exception( FIELDS_MISSING );
}
}
public function getAnswers(array $data)
{
if( !empty( $data ) ){
$right_answer=0;
$wrong_answer=0;
$unanswered=0;
$total_question = $_POST['total_num_questions'];
$keys=array_keys($data);
$order=join(",",$keys);
$query = "select id,answer from questions where id IN($order) ORDER BY FIELD(id,$order)";
$response=sqlsrv_query( $this->_con, $query) or die(SQLSRV_errors());
$user_id = $_SESSION['id'];
$score_id = $_SESSION['score_id'];
while($result=sqlsrv_fetch_array($response)){
if($result['answer']==$_POST[$result['id']]){
$right_answer++;
}else if($data[$result['id']]=='smart_quiz'){
$unanswered++;
}
else{
$wrong_answer++;
}
}
$results = array();
$results['right_answer'] = $right_answer;
$results['wrong_answer'] = $wrong_answer;
$results['unanswered'] = $unanswered;
$update_query = "update scores set right_answer='$right_answer', wrong_answer = '$wrong_answer', unanswered = '$unanswered' where user_id='$user_id' and id ='$score_id' ";
sqlsrv_query( $this->_con, $update_query) or die(SQLSRV_errors());
sqlsrv_close($this->_con);
return $results;
}
}
}
<?php
/**
#author vetripandi
#copyright http:www.vetbossel.in
*/
require_once 'messages.php';
//site specific configuration declartion
define( 'DB_HOST', 'NIKUNJ' );
define( 'DB_USERNAME', 'sa');
define( 'DB_PASSWORD', 'sql#123');
define( 'DB_NAME', 'user_login');
function __autoload($class)
{
$parts = explode('_', $class);
$path = implode(DIRECTORY_SEPARATOR,$parts);
require_once $path . '.php';
}
its the image of the data i am sending but $_POST is not getting any values and nothing happens after signup button is pressed
Your code is only running if the $_POST array is empty.
Change your code to the following.
if(!empty($_POST))
Other than that, I see no problems.
It's better practice to take the submit button as a centre of attention for the execution of the server side coding executing.
Therefore check if the $_POST data has been sent using isset:
if (isset($_POST['submit']))
{
// the data has successfully been sent
}
are you sure is's ok ?
if(empty($_POST))
you always execute code in if if $_POST is empty
if(!empty($_POST))
execute when $_POST NOT empty
This may not be your problem, but generally the submit button is
<input type="submit" value="submit">
rather than
<button type="submit">Submit</button>
From: W3schools.com
I got my mistake. I dont know how but the value of the forms were not only transferred to this php file but also in another php file names check-email.php which was part of my project which was not mentioned anywhere in register.php.
I got to know the problem by seeing some post related to this kind of problem on stack overflow where he said to check you PHP_error_log and Apache error log. The error was clearly stated there. By doing some changes to check-email.php it is working fine now. Thank you everybody for your help anyway
How to insert every value of array variable in database, whenever i try to insert value using array variable it gives me a error "Array to string conversion".Actually i want to store the attendance of students into "attendance database table", i am retrieving id and name of students from students database, this information of students is being stored in array but when i use array variable"$result" to insert the name of student into attendence_tbl database it gives me error of array to string conversion.
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="templatemo-line-header" style="margin-top: 0px;" >
<div class="text-center">
<hr class="team_hr team_hr_left hr_gray"/><span class="span_blog txt_darkgrey txt_orange">Attendance Form</span>
<hr class="team_hr team_hr_right hr_gray" />
</div>
</div>
</div>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include("config.php");?>
<div class="form-container">
<form method="post" action="" role="form">
<!-- <div class="container"> -->
<div class="col-lg-3">
<div class="form-group">
<?php
$qs=mysql_query("select * from student_table");
?>
<table border=1>
<?php
$c=0;
while($stid=mysql_fetch_row($qs))
{
?>
<tr>
<td ><?php echo $stid[0]?></td>
<td><?php echo $stid[1]?></td>
<td>
<select name="present[]" >
<option value=""> ---Select Attendence--- </option>
<option value="P"> Present </option>
<option value="A"> Absent </option>
</select></td>
</tr>
<?php
$stud= $stid[0];
$subj= $stid[1];
$location_vars = array(/*"stud" ,*/ "subj");
$result[] = compact("nothing_here", $location_vars);
$date = date('Y-m-d H:i:s');
$c++;
}
// echo "</select>"."<br>";
echo $c;
$e=0;
if(isset($_POST['present'])){
foreach($_POST['present'] as $present){
print_r($result);
$query=mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES('$stud','$stid','$present','$date')");
$e++;
}}
?>
</table>
</div>
</div> <!--col-lg-4-->
<button type="submit" name="save" value="Save" class="btn btn-success btn-sm">Save</button>
</form>
</div> <!--form-container-->
</div><!--container-->
</body>
</html>
Seems you want to put an array variable data directly into table which is supposed to throw error,
Here is the solution.
For adding all value of an array directly into table you have to use first convert array into json and then need to insert it into database. like this..
$resultJson = json_encode($result);
$query = mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES(".$stud.", ".$resultJson.", ".$present.", ".$date.")");
AND if you want to add all array value into database for each value per row separately then you have to make sure run the loop and then insert each value into database for each record.
If I understand you right you want to upload something like this:
Array([1] => '1', [2] => '2')
into a table, which would not work. So you'd have to use JSON to stringify the array. Example:
<?php
$value = 'Some string';
$value2 = 'Some other string';
$values = Array('String 1', 'String 2', 'String 3');
$json_values = json_encode($values);
$mysqli = new mysqli('HOSTNAME', 'USERNAME', 'PASSWORD', 'DATABASE'); // Connecting to SQL Server
// Checking if connection was successfull
if( $mysqli->connect_errno ){
echo 'There was an error connection to the SQL Server<br>';
echo '(' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
exit; // FAIL
}
// Preparing a statement
$stmt = $mysqli->prepare('INSERT into TABLENAME(value, value2, values) VALUES(?, ?, ?)');
// Checking if php prepared the statement successfully
if(!$stmt){
echo 'There was an error preparing the statement!';
exit;
}
if( !$stmt->bind_param('sss', $value, $value2, $json_values) ){
echo 'There was an error binding params to the statement!';
exit;
}
$stmt->execute();
?>
to post arrays into DB I use this approach:
//database connection class
class Database{
// specify your own database credentials
private $host = "YOUR HOST";
private $db_name = "DATABASE NAME";
private $username = "USERNAME";
private $password = "PASSWORD";
public $conn;
// get the database connection
public function getConnection(){ $this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
//model class
class Model{
// database connection
private $conn;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// add info to db
function create($fieldset){
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query to insert record
$query = "INSERT INTO
tbl_attendence
SET
$fieldset";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
//part that will handle the post
// get database connection
$database = new Database();
$db = $database->getConnection();
//instatiate model
$model = new Model($db);
//function that will filter posted values
function filter($value){
$value = trim($value);
$value = strip_tags($value);
$value = stripslashes($value);
$value = htmlentities($value);
return $value;
}
if(!empty($_POST)){
//Get Variables
foreach($_POST as $key => $value){
//this part will tackle values which are arrays
if(is_array($value)){
$val=implode(",",filter($value));
$groupVal[] = $val;
$groupKeys[] = $key;
}
else{
$groupVal[] = $this->filter($value);
$groupKeys[] = $key;
}
}
//count items in array to establish a limit
$limit = count($_POST);
//arranges the data into "key = value" format
for($i=0;$i<$limit;$i++){
$prepFieldset[$i] = "$groupKeys[$i] = $groupVal[$i]";
}
//prepares the fieldset to be used in SQL query
$fieldset = implode(",",$prepFieldset);
//process them in the model
$status = $model->create($fieldset);
//show response
if($status == true){
$response = 'Data saved';
}
else{
$response = 'Error when saving data';
}
}
I've been searching the internet and "pulling my hair out" for days over this. It works fine on my XAMPP localhost and was working fine on my online testing server until I updated the PHP version and had to rewrite the code due to deprecated syntax.
Basically, I'm making a backend database for photography clients. One of the tables is designed to store image information. I haven't tried to store an actual image (BLOB of some sorts), I'm just looking to store "what and where".
What seems to be happening is if I try entering the contents of a shoot directory with several hundred images, when I hit input the screen changes, then instead of telling me how many were entered, it goes to a "418 unused" page saying
The server encountered an internal error or misconfiguration and was unable to complete your request.
I've been trying to narrow down which buffers to increase or variables like "max_allowed_packet", "max_input_vars"... still no luck. I've even tried comparing the phpinfo between the two servers to find out why one works and the other doesn't...
Here's what I'm doing... the listpage
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
$database = new Database();
$db = $database->getConnection();
$colname_chk_Images = "-1";
if (isset($_GET['ShootId'])) {
$colname_chk_Images = $_GET['ShootId'];
}
$colname1_chk_Images = "NULL";
if (isset($_GET['ShootFolder'])) {
$colname1_chk_Images = $_GET['ShootFolder'];
}
$colname_get_Images = "-1";
if (isset($_SESSION['cID'])) {
$colname_get_Images = $_SESSION['cID'];
}
$entered=0; //check for already entered images
?>
<?php
$dirname=$_SESSION['cIFolder'];
$Clogin=$_SESSION['Clogin'];
$ClientID=$_SESSION['cID'];
$_SESSION['CURR_CLIENT_ID'] = $ClientID;
$maindir=$_GET['ShootFolder'];
$ShootId=$_GET['ShootId'];
$dir=$_SERVER['DOCUMENT_ROOT'].dirname($_SERVER['PHP_SELF'])."protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$_SESSION['dir']=$dir;
$dir2="/protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$dirt= "/phpThumb-master/";
$dirn= dirname($_SERVER['PHP_SELF']);
$filesArray=array_map('basename', glob($dir."/*.jpg"));
$lightbox_data= "FPAD_Lightbox";
$thumb = "$dir2/";
$notThumb = "$dir2/";
$ic = count($filesArray);
$_SESSION['SESS_TOTNUM'] = $ic;
$_SESSION['sID'] = $ShootId;
$sID = $_SESSION['sID'];
include_once 'header_a.php';
?>
<div class="container">
<?php
echo $_SESSION['SESS_TOTNUM']." images found ";
echo "for Shoot ID#: ".$_SESSION['sID']."<br>";
echo "*Note* - if input boxes come up GREEN, then images are already loaded into the database";
?>
<p>
<?php
$images1 = new Image($db);
$images1->ShootId = $colname_chk_Images;
$images1->directory = $colname1_chk_Images;
$images1->ClientID = $colname_get_Images;
$chk_Images = $images1->checkImages();
$get_Images = $images1->getImages();
$Images = array();
while ($row_get_Images = $get_Images->fetch(PDO::FETCH_ASSOC))
{
$Images[] = $row_get_Images['image_name'];
}
?></p>
<form method="POST" name="form1" id="form1" action="input.php">
<table id="clientshoots" class="table table-condensed table-bordered table-small">
<tr>
<th>image_id</th>
<th>image_name</th>
<th>image_path</th>
<th>image_path_root</th>
<th>image_size</th>
<th>directory</th>
<th width="auto">ShootId</th>
<th width="auto">ClientID</th>
<th>ClientName</th>
<th>login</th>
</tr>
<?php $ic=0;
for($i=0;$i<count($filesArray);$i++) {
$fileinfo = $filesArray[$i];
$fname=$dir."/".$fileinfo;
$fname2=$dir2."/".$fileinfo;
$size = filesize($fname);
$atime = date("F d, Y H:i:s", fileatime($fname));
$mtime= date("F d, Y H:i:s", filemtime($fname));
$perms=decoct(fileperms($fname) & 0777);
$type=filetype($fname);
$pth=realpath($fname);
$name=basename($fname);
$dn=dirname($fname2);
if (in_array($fileinfo, $Images)) {
$entered=1;
echo "<style type=\"text/css\">\n";
echo "input {\n";
echo "background-color:#00FF33;\n";
echo "}\n";
echo "</style>";
}
?>
<tr>
<td> </td>
<td><input type="text" name="image_name[]" value="<?php echo $fileinfo; ?>" readonly/></td>
<td><input type="text" name="image_path[]" value="<?php echo $dir; ?>" readonly/></td>
<td><input type="text" name="image_path_root[]" value="<?php echo $dir2; ?>" readonly/></td>
<td><input type="number" name="image_size[]" value="<?php echo $size; ?>" readonly/></td>
<td><input type="text" name="directory[]" value="<?php echo $maindir; ?>" readonly/></td>
<td><input type="number" name="ShootId[]" value="<?php echo $ShootId; ?>" readonly/></td>
<td><input type="number" name="ClientID[]" value="<?php echo $ClientID; ?>" readonly/></td>
<td><input type="text" name="ClientName[]" value="<?php echo $_SESSION['cName']; ?>" readonly/></td>
<td><input type="text" name="login[]" value="<?php echo $Clogin; ?>" readonly/></td>
</tr>
<?php next($filesArray);
$ic=$ic+1;
}
$_SESSION['SESS_IC'] = $ic;?>
</table>
<?php if ($entered == 1){
echo "Return";
} else {
echo "<input class=\"btn-primary\" style=\"background-color:\" id=\"Insert records\" type=\"submit\" value=\"Insert records\">";
}?>
<input type="hidden" name="MM_insert" value="form1">
<input type="hidden" name="sID" value="<?php echo $sID; ?>">
</form>
</div>
<br>
<!-- /container -->
<?php include 'footer_b.php'; ?>
and then the input.php page...
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
include_once 'objects/ratings.php';
$database = new Database();
$db = $database->getConnection();
$sID = $_SESSION['sID'];
$ic = $_SESSION['SESS_IC'];
$ma = $_SESSION['SESS_CLIENT_MULTI'];
$gn = $_SESSION['SESS_CLIENT_GRPNO'];
$cID = $_SESSION['cID'];
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
$image1 = new Image($db);
$count = count($_POST['image_name']);
$fileinfo = clean($_POST['image_name']);
//Check for duplicates
if($fileinfo != '') {
for($i=0;$i<$count;$i++) {
$fileinfo = clean($_POST['image_name'][$i]);
//echo $fileinfo;
$image1->image_name = $fileinfo;
$result = $image1->check4Dup();
if($result) {
if(count($result) > 0) {
$errmsg_arr[] = 'Image already entered into Database';
$errflag = true;
}
$result = NULL;
}
else {
die($e->getMessage());
}
next($count);
}
}
$image1->ic = $ic;
$num = $image1->create();
$colname_newImages = "-1";
if (isset($sID)) {
$colname_newImages = $sID;
}
$image1->ShootId = $sID;
$newImages = $image1->countOneShoot();
$row_newImages = $newImages->fetch(PDO::FETCH_ASSOC);
$totalRows_newImages = $newImages->rowCount();
$ic2 = $totalRows_newImages;
$_SESSION['SESS_TOTNUM_ENT'] = $ic2;
header("Location: rs_images.php");
include_once 'header_a.php';
?>
<div class="container">
<?php
echo "Success! Number of images entered is ".$ic2; ?>
<br><br>
<p><input name="Verify" type="button" value="Verify Inputs" onclick="MM_goToURL('parent','rs_images.php');return document.MM_returnValue"/></p>
</div>
<?php include 'footer_b.php'; ?>
And the Class file...
<?php
class Image{
// database connection and table name
private $dbh;
private $table_name = "images";
// object properties
public $image_id;
public $image_name;
public $image_path;
public $image_path_root;
public $image_size;
public $directory;
public $ShootId;
public $ClientID;
public $ClientName;
public $login;
public $ic;
public function __construct($db){
$this->dbh = $db;
}
// Clean Function
function clean($str){
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
// test function
function test(){
$ic = $this->ic;
$i=1;
$j=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
$Clogin = $login."');";
$i=$i+1;
$j=$j+1;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$Clogin;
//$stmt = $this->dbh->prepare($qry1st.$sql_array);
//$stmt->execute();
echo $qry1st.$sql_array;
}
}
// create function
function create(){
$ic = $this->ic;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = array(); // This is where we'll queue up the rows
$queue_num = 50; // How many rows should be queued at once?
$i=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
if ($i==($_SESSION['SESS_TOTNUM'])) {
$login_term = $login."');";
}
else
{
$login_term = $login."')";
$i=$i+1;
}
$sql_array[] = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$login_term;
// Add a new entry to the queue
$c=0;
if (count($sql_array) >= $queue_num)
{ // Reached the queue limit
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array)); // Insert those that are queued up
$addImages->execute();
$sql_array = array(); // Erase the queue
}//End if
}//end foreach
if (count($sql_array) > 0) // There are rows left over
{
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array));
$addImages->execute();
}
}
function checkImages(){
$query_chk_Images = "SELECT images.image_name FROM images WHERE ShootId = ? AND directory = ?";
$chk_Images = $this->dbh->prepare ($query_chk_Images);
$chk_Images->bindValue(1, $this->ShootId);
$chk_Images->bindValue(2, $this->directory);
$chk_Images->execute();
return $chk_Images;
}
// create function
function getImages(){
$query_get_Images = "SELECT * FROM images WHERE ClientID = ? ORDER BY image_name ASC";
$get_Images = $this->dbh->prepare ($query_get_Images);
$get_Images->bindValue(1, $this->ClientID);
$get_Images->execute();
return $get_Images;
}
// create function
function getImageID(){
$query_rsImageID = "SELECT * FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$rsImageID = $this->dbh->prepare($query_rsImageID);
$rsImageID->bindValue(1, $this->ShootId);
$rsImageID->execute();
return $rsImageID;
}
// create function
function get_image_id(){
$q = "SELECT image_id FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$stmt = $this->dbh->prepare($q);
$stmt->bindValue(1, $this->ShootId);
$stmt->execute();
return $stmt;
}
// create function
function countOneShoot(){
$query_newImages = "SELECT * FROM images WHERE ShootId = ?";
$newImages = $this->dbh->prepare($query_newImages);
$newImages->bindValue(1, $this->ShootId);
$newImages->execute();
return $newImages;
}
// create function
function check4Dup(){
$qry = "SELECT * FROM `images` WHERE image_name = ?";
$result = $this->dbh->prepare($qry);
$result->bindValue(1, $this->image_name);
$result->execute();
return $result;
}
}
I've striped out all the extra stuff I've tried, like entering the info one record at a time, binding the Values with colon prefixed field names instead of the ?'s. I've tried different loops. I think it comes down to trying to push too much through one query... but then why does it work on XAMPP and why was it working fine with PHP 5.2?
I appreciate any light that can be shed on this. This is my first ever post with regards to PHP, MySQL or anything site related, I've been learning this stuff as I go and had it 90% completed and debugged and when I put it online to do some real testing with the actual directories and client folders that's when I found out that between PHP 5.4 and 5.2, there have been a number of changes and I found myself rewriting almost every line to move up to either MySQLi or PDO/OOP. After doing a lot searching around the internet I've opted for the OOP approach and still need to rewrite even more of the code above to clean things up a ton, but right now I'm troubleshooting the INSERT failure which I have not been able to solve on my own or with the help of all the forums, posts and blogs I've read to date.