I have 2 problems, my first problem is that I have an error with my PHP script. It basically give me this
Fatal error: Uncaught Error: Cannot pass parameter 2 by reference in /customers/1/d/9/the-scientist.fr/httpd.www/api/addPost.php:30 Stack trace: #0 {main} thrown in /customers/1/d/9/the-scientist.fr/httpd.www/api/addPost.php on line 30
And my second problem is that I'm trying to insert an image in a row in MariaDB, I want to do the same thing as PHPMyAdmin for the image insertion in a BLOB row. So, this is my PHP script:
<?php
try
{
$db = new PDO('mysql:host=the-scientist.fr.mysql;dbname=the_scientist_fr_appli_posts;charset=utf8', 'the_scientist_fr_appli_posts', 'arthur2205');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
// $security = new White\Security;
$post = $_POST;
$img = base64_encode(file_get_contents($_FILES['img']['tmp_name']));
$title = addslashes($post['title']);
$description = addslashes($post['description']);
$fullDesc = addslashes($post['full']);
// if (!empty($title) & !empty($description) & !empty($fullDesc) & !empty($img)) {
// }
// else {
// // header("Location: form.php?error=Fill the form!");
// }
$stmt = $db->prepare("INSERT INTO posts (title, description, img, fullDesc, likes) VALUES (:title, :description, :img, :fullDesc, :likes)");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':img', $img);
$stmt->bindParam(':fullDesc', $fullDesc);
$stmt->bindParam(':likes', 0);
$stmt->execute();
// header("Access-Control-Allow-Origin: *");
header("Location: form.php?error=$sql");
Also, this is the form:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.3.2/css/ionic.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form enctype="multipart/form-data" class="form" id="form" action="./addPost.php" method="POST">
<div class="list">
<label class="item item-input">
<input type="text" placeholder="Titre" class="AddPosttitle" name="title">
</label>
<label class="item item-input">
<input class="description" type="text" placeholder="Mot Clés" maxlength="60" name="description">
</label>
<label class="item item-input">
<div>
<span id='button_upload'>Image : </span>
<input type='file' class="img" name="img">
</div>
</label>
<label class="item item-input">
<textarea placeholder="Description" class="full" name="full"></textarea>
</label>
<div class="padding">
<button class="button button-block button-positive submit-btn" type="submit">
Envoyer
</button>
</div>
</div>
</form>
<style type="text/css">
.form {
background: #FFF;
}
</style>
<?php
if (!empty($_GET['error'])){
?>
<script type="text/javascript">
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
alert(findGetParameter("error"));
</script><?php
}
?>
I think that at this point, my problem is pretty clear, if you need more informations, ask in the comment section 😄.
About the first problem: You are using:
$stmt->bindParam(':likes', 0);
bindParam() expects a parameter, a variable.
If you just want to bind a value, you should use bindValue() instead:
$stmt->bindValue(':likes', 0);
Related
This is the extended question of the thread implementing php long polling
I got the solutions for that. But in my server.php i am displaying a form which will be having few input fields. This should display in #response area. Now i am able to display the same on instant basis. As it loads on seconds basis, i am not able to enter anything on any input boxes. Here is my display page
<?php
ob_start();
include('includes/sessions.php');
include('includes/config.php');
include('includes/functions.php');
$grp_id = $_GET['id'];
?>
<!DOCTYPE html>
<head>
<!-- head section -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
function getContent(timestamp)
{
var queryString = {'timestamp' : timestamp, 'id' : <?php echo $grp_id; ?>};
$.ajax(
{
type: 'GET',
url: 'http://localhost/folder/server.php',
data: queryString,
success: function(data){
// put result data into "obj"
var obj = JSON.parse(data);
// put the data_from_file into #response
$('#response').html(obj.data_from_file);
// call the function again, this time with the timestamp we just got from server.php
getContent(obj.timestamp);
}
}
);
}
// initialize jQuery
$(function() {
getContent();
});
</script>
</head>
<body<?php if ($body_classes) { echo ' class="' . $body_classes . '"'; } ?>>
<div id="page-content" class="block">
<div class="row gutter30">
<div class="col-xs-12">
<div id="response"></div>
<!--Contents in server.php will display according to the condition changes in database-->
</div>
</div>
</div>
server.php
<?php
set_time_limit(0);
$data_source_file = 'data.txt';
include('includes/sessions.php');
include('includes/config.php');
include('includes/functions.php');
// main loop
while (true) {
// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : null;
// PHP caches file data, like requesting the size of a file, by default. clearstatcache() clears that cache
// clearstatcache();
// get timestamp of when file has been changed the last time
// $last_change_in_data_file = filemtime($data_source_file);
// Create database
$sql = "SELECT max(gid) FROM base_grp WHERE gid=".$_GET['id']."";
$result = mysqli_query($conn, $sql);
$last_change_in_data_file = mysqli_fetch_array($result, MYSQLI_NUM)[0];
// if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {
$sql = "SELECT is_set FROM base_grp WHERE gid =".$_GET['id']."";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if($row['is_set'] == 0)
{
$data .= '<form name="frm" method="post" action="show_data.php">
<div class="row gutter30" style="margin-top:20px;">
<div class="form-group">
<img src="img/img1.png" class="image" />
<input type="text" name="img1" class="form-control" />
<input type="hidden" name="img1_id" value="3" />
</div>
<div class="form-group">
<img src="img/img2.png" class="image" />
<input type="text" name="img2" class="form-control" />
<input type="hidden" name="img2_id" value="4" />
</div>
<div class="form-group">
<img src="img/img3.png" class="image" />
<input type="text" name="img3" class="form-control" />
<input type="hidden" name="img3_id" value="2" />
</div>
<div class="form-group">
<img src="img/img4.png" class="image" />
<input type="text" name="img4" class="form-control" />
<input type="hidden" name="img4_1" value="1" />
</div>
<button type="submit" name="lock" class="btn btn-sm btn-success">SUBMIT</button>
</div>
</form> ';
$last_change_in_data_file = $row["gid"];
}
else if($row['is_set'] = 1)
{
$data .= "<div class='row gutter30' style='margin-top:20px;'>
<div class='col-xs-3'>
<img src='img/img1.png' class='image' /> </div>
<div class='col-xs-3'>
<img src='img/img2.png' class='image' /> </div>
<div class='col-xs-3'>
<img src='img/img3.png' class='image' /> </div>
<div class='col-xs-3'>
<img src='img/img4.png' class='image' /> </div>
</div>
";
$last_change_in_data_file = $row["gid"];
}
$last_change_in_data_file = $row["gid"];
}
}
// mysqli_close($conn);
// put data.txt's content and timestamp of last data.txt change into array
$result = array(
'data_from_file' => $data,
'timestamp' => $last_change_in_data_file
);
mysqli_close($conn);
// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
echo $json;
// leave this loop step
break;
} else {
// wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
sleep( 1 );
continue;
}
}
Not getting how to make the entry ...
Can somebody suggest me where i am going wrong?. Thanks!
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
This is my php and html code.
<!--PHP -->
<?php # Script 9.5 - register.php #2
// This script performs an INSERT query to add a record to the events table
$page_title = 'Machinovate | Add Events';
include ('header_after_login.php');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../../mysqli_connect.php'); // Connect to the db.
$dbc = mysqli_connect("localhost", "username", "password", "machinovate");
$errors = array(); // Initialize an error array.
// Check for a event_date:
if (empty($_POST['event_date']))
{
$errors[] = 'You forgot to enter the event date.';
}
else
{
$event_date = mysqli_real_escape_string($dbc, trim($_POST['event_date']));
}
// Check for a event name:
if (empty($_POST['event_name']))
{
$errors[] = 'You forgot to enter the event name.';
}
else
{
$event_name = mysqli_real_escape_string($dbc, trim($_POST['event_name']));
}
// Check for an event_place address:
if (empty($_POST['event_place']))
{
$errors[] = 'You forgot to enter your event place .';
}
else
{
$event_place = mysqli_real_escape_string($dbc, trim($_POST['event_place']));
}
// Check for an image:
if (is_uploaded_file ($_FILES['image']['tmp_name']))
{
// Create a temporary file name:
$temp = '../../uploads/' . md5($_FILES['image']['name']);
// Move the file over:
if (move_uploaded_file($_FILES['image']['tmp_name'], $temp))
{
echo '<p>The file has been uploaded!</p>';
// Set the $i variable to the image's name:
$i = $_FILES['image']['name'];
}
else
{ // Couldn't move the file over.
$errors[] = 'The file could not be moved.';
$temp = $_FILES['image']['tmp_name'];
}
}
else
{ // No uploaded file.
$errors[] = 'No file was uploaded.';
$temp = NULL;
}
if (empty($errors))
{ // If everything's OK.
// Register the event in the database...
// Make the query: **made by drei*
$q = "INSERT INTO events (event_date, event_name, event_place) VALUES (?, ?, ?);
INSERT INTO event_pictures (event_id, image_name) VALUES ((SELECT event_id FROM events WHERE event_date = ?), ?);
";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'ssss', $event_date, $event_name, $event_place, $event_date, $i);
mysqli_stmt_execute($stmt);
//Check the results...
if (mysqli_stmt_affected_rows($stmt) == 1)
{ // If it ran OK.
// Print a message:
echo '<h1>Thank you!</h1>
<p>An event has been added!!</p><p><br /></p>';
// Rename the image:
$id = mysqli_stmt_insert_id($dbc); // Get the print ID.
rename ($temp, "../../uploads/$id");
// Clear $_POST:
$_POST = array();
}
else
{ // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">The event could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($stmt);
} //end of $errors IF
// Delete the uploaded file if it still exists:
if ( isset($temp) && file_exists ($temp) && is_file($temp) )
{
unlink ($temp);
}
} //End of Submission IF
// Check for any errors and print them:
if ( !empty($errors) && is_array($errors) )
{
echo '<h1>Error!</h1>
<p style="font-weight: bold; color: #C00">The following error(s) occurred:<br />';
foreach ($errors as $msg)
{
echo " - $msg<br />\n";
}
echo 'Please reselect the print image and try again.</p>';
}
?>
<!--HTML -->
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../styles/bootstrap.min.css">
<link rel="stylesheet" href="../styles/main.css">
<link rel="stylesheet" href="../styles/admin.css">
<style type="text/css">
.item {
margin: 1em 0;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<form enctype="multipart/form-data" action="add_events.php" method="post" class="form-horizontal col-sm-6" role="form">
<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
<div class="form-group">
<legend>Add Events</legend>
<fieldset><legend>Fill out the form to add an event:</legend>
</div>
<div class="form-group">
<label for="last-name" class="col-sm-3 control-label">Starting Date:</label>
<div class="col-sm-9">
<input placeholder="Enter event's date: "type="text" class="form-control" id="date-start" name="event_date" maxlength="40" value="<?php if (isset($_POST['event_date'])) echo $_POST['event_date']; ?>" />
</div>
</div>
<div class="form-group">
<label for="last-name" class="col-sm-3 control-label">Event Name:</label>
<div class="col-sm-9">
<input placeholder="Enter event name"type="text" class="form-control" id="event-name" name="event_name" maxlength="40" value="<?php if (isset($_POST['event_name'])) echo $_POST['event_name']; ?>" />
</div>
</div>
<div class="form-group">
<label for="event_place" class="col-sm-3 control-label">Event Venue: </label>
<div class="col-sm-9">
<input placeholder="Enter the event's venue" type="event_place" class="form-control" id="event-place" name="event_place" maxlength="20" value="<?php if (isset($_POST['event_place'])) echo $_POST['event_place']; ?>" />
</div>
</div>
<div class="form-group">
<label for="image_name" class="col-sm-3 control-label">Upload Image:</label>
<div class="col-sm-9">
<div class="img-input">
<input name="image" id="image" type="file" class="item" value="Browse Image"/>
</div>
<!--<button id="add-img-btn" type="button" class="btn btn-default">
<span class="glyphicon glyphicon-plus"></span>
</button>-->
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button type="Add" class="btn btn-primary">Add event</button>
</div>
</div>
</form>
</div> <!-- /.row -->
</div> <!-- /.container -->
<!--<script type="text/javascript" src="../scripts/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="../scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#add-img-btn').on('click',function() {
$('.img-input').append($('<input name="image_name" id="image_name" type="file" class="item" value="Browse Image"/>'));
});
});
</script>-->
</body>
</html>
But after running it, I always get an error of:
' Warning: mysqli_stmt_bind_param() expects parameter 1 to be
mysqli_stmt, boolean given in
C:\Users\Angela\Documents\3CSC\ICS114_installers\XAMPP\htdocs\Machinovate\web\admin\add_events.php
on line 89
Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt,
boolean given in
C:\Users\Angela\Documents\3CSC\ICS114_installers\XAMPP\htdocs\Machinovate\web\admin\add_events.php
on line 90
Warning: mysqli_stmt_affected_rows() expects parameter 1 to be
mysqli_stmt, boolean given in
C:\Users\Angela\Documents\3CSC\ICS114_installers\XAMPP\htdocs\Machinovate\web\admin\add_events.php
on line 93 System Error The event could not be registered due to a
system error. We apologize for any inconvenience.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'INSERT INTO event_pictures (event_id, image_name) VALUES
((SELECT event_id FROM ' at line 2
Query: INSERT INTO events (event_date, event_name, event_place) VALUES
(?, ?, ?); INSERT INTO event_pictures (event_id, image_name) VALUES
((SELECT event_id FROM events WHERE event_date=?), ?);
Warning: mysqli_close() expects parameter 1 to be mysqli, boolean
given in
C:\Users\Angela\Documents\3CSC\ICS114_installers\XAMPP\htdocs\Machinovate\web\admin\add_events.php
on line 119'
This could be the problem:
Your ssss here doesn't match the number of your variables.
mysqli_stmt_bind_param($stmt, 'ssss', $event_date, $event_name, $event_place, $event_date, $i);
You have 4 s here while you have 5 variables. Try this
mysqli_stmt_bind_param($stmt, 'sssss', $event_date, $event_name, $event_place, $event_date, $i);
I'd suggest you to try some debugging.
For example,
$q = "INSERT INTO events (event_date, event_name, event_place) VALUES (?, ?, ?);
INSERT INTO event_pictures (event_id, image_name) VALUES ((SELECT event_id FROM events WHERE event_date = ?), ?);
";
$stmt = mysqli_prepare($dbc, $q) or die( mysqli_error($dbc) );
mysqli_stmt_bind_param($stmt, 'ssss', $event_date, $event_name, $event_place, $event_date, $i);
mysqli_stmt_execute($stmt) or die( mysqli_stmt_error($stmt) );
This will notify you about the possible SQL error.
Besides, I think you should be using mysqli_multi_query here.
Refer to this: Mysqli Multi queries
Hope this helps.
Peace! xD
First of all before i show you the code i will explain how my webpage works.
User selects date -> AJAX Calls On Date Change
Resulting PHP data displays in two sections on page.
First Section is Orders Table Contents
Second Section is Items Table Contents (not including the items inside Orders)
What i am trying to add is functionality to 3 buttons that will change the tables dynamically using AJAX.
I currently have working non ajax requests.
Here is the Code:
$(document).ready(function(){
$('.date-picker').change(function(){
$.ajax({
type: 'POST',
url: 'php/getproduct.php',
data: {dateorderpicker: $('.date-picker').val()},
dataType: 'JSON',
success: function(data)
{
$("#cartrow").html(data.result_1);
$("#otheritems").html(data.result_2);
}
});
});
});
PHP file for Current AJAX:
session_start();
include('db_config.php');
$datepicker = $_POST['dateorderpicker'];
$sql = "SELECT * FROM orders WHERE deliveryDate = ? AND customerId = ? ";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $datepicker, PDO::PARAM_STR);
$stmt->bindParam(2, $_SESSION['customer_id'], PDO::PARAM_INT);
$stmt->execute();
$container = array();
$data['result_1'] = $data['result_2'] = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$container[] = "'{$row['itemName']}'"; // put them inside a temporary container
$data['result_1'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/edit.php" method="post" class="form-inline pull-right">
<h3>' . $row['itemName'] . '</h3>
<h4>Total Price: $'.$row['price'].'</h4>
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>Our best seller. Full of flavour.</p>
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" value="' . $row['qty'] . '">
</div>
</div>
<input type="hidden" name="id" value="'.$row['id'].'">
<button type="submit" name="update" class="btn btn-primary">Update</button>
<button type="submit" name="delete" class="btn btn-primary">Remove</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
if(!empty($container)){
$excluded_names = implode(',', $container);
$sql = "SELECT * FROM item WHERE itemName NOT IN($excluded_names)";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input id="itemname" type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input id="price" type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input id="description" type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input id="qty" type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
else
{
$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
echo json_encode($data);
exit;
Both Update and Delete PHP file:
include('db_config.php');
if (isset($_POST['update']))
{
$qty = $_POST['qty'];
$id = $_POST['id'];
echo $id;
$sql = "UPDATE orders SET qty=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($qty,$id));
header('Location: ../order.php');
}
if (isset($_POST['delete']))
{
$id = $_POST['id'];
$sql = "DELETE FROM orders WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
header('Location: ../order.php');
}
The code above needs to be converted to AJAX, and both sections on the page using ajax should update the table automatically. It might be that you will call the first ajax query to reload the tables correctly?
Thanks for having a look at this.
I am having trouble wrapping my head around how i should get this work.
Alex
It is easy you can give a class (NOTE : yes class ) to your update button and similarly to delete button
Suppose your update button has class "update_task"
but your content was added to DOM after DOM already loaded, so you will need to create two ajax request with DELEGATE Methods for delete and update.
For delegate reference -
http://api.jquery.com/delegate/
// for update
$("body").delegate(".update_task","click",function(){
current_id = $(this).previous("input:hidden").val() // for current update button id,
$.ajax({
type: 'POST',
url: 'php/update_product.php',
data: {id: current_id, othervalues: other_value_of_choice},
dataType: 'JSON',
success: function(data)
{
if(data==1)
{
// what ever you want to do if data has been updated
}
}
});
});
Send AJAX request to PHP for update/delete. Return result of operation (true/false).
If result is true, update/remove from html with javascript(jquery).
By the way, don't use redirect, when you call php via ajax.
I try to upload an image, but it is not working. Other variables I have set are inserted into database, but image file is not... I was trying to check submit with isset, but it is not working. Where is my error?
Thanks for your help.
PHP file:
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno) {
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)) {
$i1 = strrpos($upload,".");
if (!$i1) {
return "";
}
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = copy($_FILES['upload']['tmp_name'], $newname1);
} else {
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>
This is my HTML file:
<form class="cmxform form-horizontal tasi-form" name="form2" id="form2" method="post" action="">
<div class="form-group ">
<label for="icode" class="control-label col-lg-2">Item Code</label>
<div class="col-lg-10">
<input class=" form-control" id="icode" name="icode" type="text" />
</div>
</div>
<div class="form-group ">
<label for="iname" class="control-label col-lg-2">Item Name</label>
<div class="col-lg-10">
<input class=" form-control" id="iname" name="iname" type="text" />
</div>
</div>
<div class="form-group ">
<label for="brandname" class="control-label col-lg-2">Brand Name</label>
<div class="col-lg-10">
<input class=" form-control" id="brandname" name="brandname" type="text" />
</div>
</div>
<fieldset style="width:48%; float:left;"> <!-- to make two field float next to one another, adjust values accordingly -->
<label>Doc 2</label>
<input style="margin: 0 10px;" type="file" name="upload" size="50">
</fieldset>
Add 'enctype="multipart/form-data"' to your form tag attributes, you can read more about file uploading here.
Also consider checking the values of the post, because your current method can get you sql injections
add form attribute enctype="multipart/form-data"
You have not proper syntax used and also use 'enctype="multipart/form-data"'.
I have implemented your code
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno){
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)){
$i1 = strrpos($upload,".");
if (!$i1) { return ""; }
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = $_FILES['upload']['tmp_name'], $newname1;
}else{
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
In html code:
<select name="123023d">
<option value="default">Not Share</option>
<option value="read">Read Only</option>
<option value="edit">Editable</option>
</select>
In php code:
$rights=$_POST['123023d'];
Why i can not retrieve the value of this select box?
Notice: Undefined index: 123023d in C:\xampp\htdocs\fyp\list\add.php on line 87
Thank you.
I am sure it is in the form and it is a post method. It is located after foreach ($result as $set) as you can see i draw some sql value to generate that select box and the name of the select box is userID
Whole part:
<form id="addlist" method="post" action="add.php" >
<h1>Create your new subscriber list</h1>
<p>Create a new list before adding subscriber <label class="right"><em class="dot">*</em> indicates required</label></p>
<label><em class="dot">*</em> List name:
<span class="small">Add your list name</span>
</label>
<input id="lname" name="lname" class="required" />
<div class="spacer"></div>
<label>Reminder:
<span class="small">Remind the details of your list</span>
</label>
<textarea id="creminder" name="creminder" cols="52" ></textarea>
<div class="spacer"></div>
<div class="spacer"></div>
<p>Email me when ...</p>
<label>People subscribe:</label> <input type="checkbox" class="checkbox" name="subscribe" value="1">
<label>People unsubscribe:</label> <input type="checkbox" class="checkbox" name="unsubscribe" value="1">
<div class="spacer"></div>
</div>
</br>
<div id="stylized" class="myform">
<p>Permission Setting ...</p>
<label>Open to other users:</label> <input type="checkbox" class="checkbox" name="public" value="1">
Or
<div class="spacer"></div>
Select the permission for individual user:
<?
$sql =
"SELECT UserID,Name,Rights,Position
FROM user
WHERE UserID != ?
AND Rights != 'Admin'
";
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));
$num_rows= $stmt->rowCount();
if ($num_rows != 0){
$result = $stmt->fetchAll();
?>
<table width="100%" class="display" id="viewSub">
<thead>
<tr>
<th field="col1" width="40%">Name:</th>
<th field="col2" width="40%">Position:</th>
<th field="col2" width="20%">Permission:</th>
</tr>
</thead>
<tbody>
<?
foreach ($result as $set)
{
echo "<tr><td>".$set['Name']."</td><td>".$set['Position']."</td><td><select name=".$set['UserID']."><option value='default'>Not Share</option><option value='read'>Read Only</option><option value='edit'>Editable</option></select></td></tr>";
}
?>
</tbody>
</table>
<?
}
else
echo "There is no another user in this system";
?>
<input class="submit" type="submit" name="submit" value="Submit"/>
<div class="spacer"></div>
</form>
add.php which is the form and the result process
<?
include("../connection/conn.php");
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST"){
print_r($_POST);
exit();
if (!isset($_POST['subscribe']))
$_POST['subscribe']=0;
if (!isset($_POST['unsubscribe']))
$_POST['unsubscribe']=0;
if (!isset($_POST['public']))
$_POST['public']=0;
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$listName = $_POST['lname'];
$listRemindSub = $_POST['subscribe'];
$creator = $_SESSION['username'];
$listRemindUnSub = $_POST['unsubscribe'];
$isPublic = $_POST['public'];
$listReminder = $_POST['creminder'];
$query="INSERT INTO list (ListID,ListName,Creator,IsRemindSub,IsRemindUnSub,IsPublic,CreateDate,Reminder) VALUES ('',?,?,?,?,?,CURDATE(),?)";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $listName , PDO::PARAM_STR);
$stmt->bindParam(2, $creator, PDO::PARAM_STR);
$stmt->bindParam(3, $listRemindSub, PDO::PARAM_INT);
$stmt->bindParam(4, $listRemindUnSub, PDO::PARAM_INT);
$stmt->bindParam(5, $isPublic, PDO::PARAM_INT);
$stmt->bindParam(6, $listReminder, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
$conn->rollBack();
}
try {
$lastID=$conn->lastInsertId();
$query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'Email','{email}')";
$stmt = $conn->prepare($query);
$stmt->execute();
$query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'FirstName','{fname}')";
$stmt = $conn->prepare($query);
$stmt->execute();
$query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'LastName','{lname}')";
$stmt = $conn->prepare($query);
$stmt->execute();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
$conn->rollBack();
}
try{
$sql = '
SELECT UserID
FROM user
WHERE Rights != ?';
$stmt = $conn->prepare($sql);
$stmt->execute(array('admin'));
$result= $stmt->fetchAll();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
foreach ($result as $set)
{
if ($set['UserID']==$_SESSION['username'])
$rights='edit';
else
{$rights=$_POST[$set["UserID"]];
$rights=$_POST['123023d'];}
if ($rights != 'default' || $set['UserID']==$_SESSION['username'] || $_POST['public']==0)
{
$user=$set['UserID'];
try {
$query="INSERT INTO user_list(UserID,ListID,UserRights) VALUES ('$user',$lastID,'$rights')";
$stmt = $conn->prepare($query);
$stmt->execute();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
$conn->rollBack();
}
}
}
$conn = null;
?>
<div id="stylized" class="myform">
<div style="text-align:center;font-weight:bold;">You have created a list. By default Mail Address, First Name , Last Name is in your list. Add more field if you want. <a href='add.php'>Back</a></div>
<div class="spacer"></div>
</div>
<?
}else{?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
#import "../plugin/easyui/themes/default/easyui.css";
#import "../plugin/easyui/themes/icon.css";
#import "../style/form.css";
#import "../plugin/datatable/media/css/demo_page.css";
#import "../plugin/datatable/media/css/demo_table.css";
</style>
<script src="../plugin/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="../plugin/easyui/jquery.easyui.min.js"></script>
<script src="../plugin/jquery.validate.min.js"></script>
<script type="text/javascript" src="../plugin/datatable/media/js/jquery.dataTables.js"></script>
<script src="../plugin/jquery.form.js"></script>
<script>
$(document).ready(function(){
$("#addlist").validate();
});
$(document).ready(function() {
$('#viewSub').dataTable();
} );
</script>
</head>
<body>
<div id="stylized" class="myform">
<form id="addlist" method="post" action="add.php" >
<h1>Create your new subscriber list</h1>
<p>Create a new list before adding subscriber <label class="right"><em class="dot">*</em> indicates required</label></p>
<label><em class="dot">*</em> List name:
<span class="small">Add your list name</span>
</label>
<input id="lname" name="lname" class="required" />
<div class="spacer"></div>
<label>Reminder:
<span class="small">Remind the details of your list</span>
</label>
<textarea id="creminder" name="creminder" cols="52" ></textarea>
<div class="spacer"></div>
<div class="spacer"></div>
<p>Email me when ...</p>
<label>People subscribe:</label> <input type="checkbox" class="checkbox" name="subscribe" value="1">
<label>People unsubscribe:</label> <input type="checkbox" class="checkbox" name="unsubscribe" value="1">
<div class="spacer"></div>
</div>
</br>
<div id="stylized" class="myform">
<p>Permission Setting ...</p>
<label>Open to other users:</label> <input type="checkbox" class="checkbox" name="public" value="1">
Or
<div class="spacer"></div>
Select the permission for individual user:
<?
$sql =
"SELECT UserID,Name,Rights,Position
FROM user
WHERE UserID != ?
AND Rights != 'Admin'
";
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));
$num_rows= $stmt->rowCount();
if ($num_rows != 0){
$result = $stmt->fetchAll();
?>
<table width="100%" class="display" id="viewSub">
<thead>
<tr>
<th field="col1" width="40%">Name:</th>
<th field="col2" width="40%">Position:</th>
<th field="col2" width="20%">Permission:</th>
</tr>
</thead>
<tbody>
<?
foreach ($result as $set)
{
echo "<tr><td>".$set['Name']."</td><td>".$set['Position']."</td><td><select name=".$set['UserID']."><option value='default'>Not Share</option><option value='read'>Read Only</option><option value='edit'>Editable</option></select></td></tr>";
}
?>
</tbody>
</table>
<?
}
else
echo "There is no another user in this system";
?>
<input class="submit" type="submit" name="submit" value="Submit"/>
<div class="spacer"></div>
</form>
<div class="spacer"></div>
</div>
<br><br><br>
<div id="stylized" class="myform">
<?
try{
$sql = '
SELECT *
FROM list,user_list
WHERE user_list.UserID=?
AND list.ListID=user_list.ListID
';
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));
$result= $stmt->fetchAll();
$num_rows= $stmt->rowCount();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
$conn = null;
if ($num_rows == 0) {
echo '<div style="text-align:center;font-weight:bold;">You have not created any list yet.</div>';}
else {
echo '<h1>Your Subscriber List</h1> <p>You have created '.$num_rows.' list(s).</p>';
foreach ($result as $set)
{
echo '<div style="font-weight:bold;">List Name : '.$set['FromName'].'</div><br>';
echo '<div style="font-weight:bold;">Subscriber : </div><br>';
echo '<div style="font-weight:bold;">Create Date : '.$set['CreateDate'].'</div><br>';
echo '<hr>';
}}
?>
<div class="spacer"></div>
</div>
</div>
</body>
</html>
<?
}
?>
Note the method you are using to submit the form. There are two general ways
GET Method <form method="GET" ... >
This is generally retrieved by using
echo $_GET['123023d'];
POST Method <form method="POST" ... >
This is generally retrieved by using
echo $_POST['123023d'];
If no method is defined, by default, it will be submitted using GET method so, use
$rights=$_GET['123023d'];
Update
I found your problem, there is no quotes in the title of select box
<select name=".$set['UserID'].">
Change it to this. You have to provide the quotes and escape them as well.
<select name=\"".$set['UserID']."\">
Update 2
Credit to #zerkms
The another problem was starting the name with a numeric value instead of a alphabetically character.
<select name="123023d">
Make sure you dont start with numbers like
<select name="a123023d">
How to retrieve value from a select box?
it is stored in the $_POST['123023d'] or $_GET['123023d'] variable depends on the method used.
If it is a 'post' request , use :
$rights=$_POST['123023d'];
For 'get' requests :
$rights=$_GET['123023d'];