i'm trying to insert data to MySQL from a dynamic form with jQuery. For the record, I'm using Twitter Bootstrap. I actually achieved insert "rows" but with no data. The best help I found right now is this here for the insert to MySQL and here to jQuery script.
Thanks in advance for taking time for this.
File: add.php
<form action="../reglas/insert.php" method="post" class="form-horizontal">
<div class="container">
<div id="content">
<div class="row">
<a class="add_line btn btn-small" href="#" style="margin-left:5px">+</a>
</div>
<br>
</div>
</div>
</div>
</div>
<div style="margin:20px auto; width:80px;">
<input class="btn btn-success" type="submit" value="Guardar">
</div>
</form>
<script>
$("#content").delegate(".add_line", "click", function() {
var content = '<div class="row">' +
'<div class="span3"><div class="input-append"><input type="text" class="span2 text-right" placeholder="0.00" id="enganche" name="enganche" value="" /><span class="add-on">%</span></div></div>' +
'<div class="span3"><div class="input-append"><input type="text" class="span2 text-right" placeholder="0.00" id="comision" name="comision" value="" /><span class="add-on">%</span></div></div>' +
'<div class="span3"><div class="input-append"><input type="text" class="span2 text-right" placeholder="0.00" id="r1" name="r1[]" value="" /><span class="add-on">%</span></div></div>' +
'<div class="span2"><div class="input-append"><input type="text" class="span1 text-right" placeholder="0.00" id="r2" name="r2[]" value="" /><span class="add-on">%</span></div></div>'+
'<a class="del_line btn btn-small" href="#" style="margin-left:5px">-</a> ' +
'<br><br>'+
'</div>';
$("#content").append(content);
return false;
});
$("#content").delegate(".del_line", "click", function() {
$(this).parent().remove();
return false;
});
</script>
File: insert.php
The Connection:
$con=mysqli_connect("$host","$username","$password","$db_name");
mysqli_autocommit($con, false);
$flag=true;
The query:
$query="
INSERT INTO $tbl_name(
the_input,
)
VALUES (
'$the_input',
)";
The "for":
for ($i = 0; $i < count($_POST['the_input']); $i++) {
$the_input = $_POST['the_input'][$i];
$result = mysqli_query($con, $query);
if (!$result) {
$flag = false;
echo "Error details: " . mysqli_error($con). ". ";
}
}
if ($flag) {
mysqli_commit($con);
echo "Done!";
}
mysqli_close($con);
?>
Okey dokey.
First things first:
$.delegate() is deprecated so unless you are using a version that is < jQuery 1.7 (which is many versions ago) you should migrate to $.on() event binder/delegator function. This will ensure that your code is future proof (at least until they change the api again!)
Secondly:
I am assuming you have wrapped your data in a form tag and the values are actually getting send to the recieving page here is how I would do it:
if(isset($_POST['the_input']))
{
//create connection object;
$mysqli = new mysqli($host,$username,$password,$db_name);
$query = "INSERT INTO `the_input` VALUES (";
//construct the query. Get the the_input data and paramater string (required for stmt binding)
foreach($_POST['the_input'] as $value)
{
$query .= $value . ",";
}
//remove trailing comma
$query = substr($query, 0, strlen($query)-1);
$query .= ")";
//this is just so you can see what the loop did and test the output of the query, remove this when you're confident
echo "The constructed query string is: " . $query
if($mysqli->query($query) == false)
{
trigger_error($mysqli->error);
} else {
echo "Success! Check the DB!";
}
} else {
Echo "No POST data was recieved";
}
Related
I am created form to select value to display in my page table.Below is my code to select multiple values and search to display, but it is not displaying the selected values (type and dates) in multiple dropdownlist. Anyone can help me solve this problem? Thanks.
My frontend coding:
<div class="box inverse">
<div class="row">
<div class="col-lg-12">
<header>
<h5>Search</h5>
</header>
<form id="transaction_search">
<div class="form-group">
<div class="col-lg-12">
<div class="col-lg-3">
</div>
<div class="col-lg-12">
<div class="form-group">
<div class="col-lg-12">
<label for="text1" class="form-group control-label col-lg-2"><?php echo $language['type']; ?>:</label>
<div class="col-lg-5">
<select id="select_type" class="form-group form-control required"">
<option value="transfer" selected><?php echo $language["transfer"]; ?></option>
<option value="withdraw"><?php echo $language["withdraw"]; ?></option>
<option value="upgrade"><?php echo $language["upgrade"]; ?></option>
<option value="register"><?php echo $language["register"]; ?></option>
<option value="receive"><?php echo $language["receive"]; ?></option>
</select>
</div>
</div>
</div>
<div class="col-lg-12 form-group">
<label for="text1" class="form-group control-label col-lg-2">Date Range:</label>
<div class="col-lg-2">
<?php echo custom_period_opt(); ?>
</div>
<label for="text1" class="form-group control-label col-lg-2">Date Created:</label>
<div class="col-lg-2">
<input type="text" class="form-group form-control datepicker" id="start_date" name="start_date" data-date-format="dd-mm-yyyy" title="" value="<?php echo $new_cur_date; ?>" readonly>
</div>
<label for="text1" class="form-group control-label col-lg-2">To</label>
<div class="col-lg-2">
<input type="text" class="form-group form-control datepicker" id="end_date" name="end_date" data-date-format="dd-mm-yyyy" title="" value="<?php echo $new_cur_date; ?>" readonly>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-12" style="text-align:center; padding-bottom:10px; padding-top:10px;">
<button id="search" type="button" class="btn btn-sm btn-primary" onclick="search_('transaction_search','transaction_result','transaction_table')">Search</button>
<button id="clear" type="button" class="btn btn-sm btn-default" onclick="clearData()">Clear</button>
</div>
<div class="body" id="transaction_result" style="overflow:auto;">
</div><!--body-->
</form>
</div>
</div>
My backend coding (This is part of coding I try to select "Withdraw" option to test output, but did't display any data in the table. This coding is want to select "withdraw" and select what I choose the "date"):
<?php
foreach ($_POST as $key => $value) {
$_POST[$key] = trim(preg_replace('/\s+/', ' ', ($value)));
}
$arr_val = $_POST;
$loc = $arr_val['loc'];
$action = $arr_val['action'];
$select_type = $_POST['select_type'];
unset($arr_val['loc']);
unset($arr_val['action']);
unset($arr_val['select_type']);
$tbl_name = 'withdrawal_record';
if ($action == 'search' && $select_type == 'withdraw' ) {
if ($_POST['select_type'] != '' || $_POST['start_date'] != '' || $_POST['end_date'] != '' ) {
$sql = 'SELECT * FROM ' . $tbl_name . ' WHERE id is not null';
if($_POST['start_date']!='' && $_POST['end_date']!= '') {
$sql .=' and a.created between "' . date('Y-m-d', strtotime($_POST['start_date'])) . '" and "' . date('Y-m-d', strtotime($_POST['end_date'])) . '"';
}
$result_arr['sql'] = $sql;
$result_arr = get_data_list($sql);
$i = 1;
echo '<table id="dataTable_1" class="dataTable table table-bordered table-condensed table-hover table-striped" style="padding:0px;" border="1">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody>';
foreach ($result_arr as $rs_search) {
echo "<tr>";
echo "<td>" . $i++ . "</td>";
echo "<td>" . $rs_search['created'] . "</td>";
echo "<td>" . $rs_search['withdraw_amount'] . "</td>";
echo '</td>';
echo "</tr>";
}
echo '</tbody>';
echo '</table>';
}
}
?>
Below is jquery function:
function search_(form_id, div_id, act_file) {
var action = 'search';
var extra = '&action=' + action;
var serialized = $('#' + form_id).serialize();
var form_data = serialized + extra;
$.ajax({
//dataType: 'json',
type: 'POST',
url: '?f=' + act_file,
data: form_data,
beforeSend: function() {
show_overLay();
$('#' + div_id).html('');
},
success: function(data) {
hide_overLay('');
if (data) {
$("#" + div_id).append(data);
$('.dataTable').dataTable({
pageLength: 25,
destroy: true
});
} else {
hide_overLay("Please fill in the field.");
}
//console.log(data);
}
});
}
Below is my "withdrawal_record" table:
withdrawal_record
Below is my output, and didn't show the data what I select. Actually I want to select date between 04/11/19 and 07/11/19 and select type is "Withdraw" :
Output 1
If success , that will show like below the output picture:
Output 2
Error output:
Output 3
In html add multiple attribute to select :
<select id="select_type" class="form-group form-control required" multiple>
In JQuery make these changes:
Remove these :
var action = 'search';
var extra = '&action=' + action;
var serialized = $('#' + form_id).serialize();
var form_data = serialized + extra;
And in Ajax request:
Remove these lines:
data: form_data,
Add these lines:
data:{action:"search","loc":$("#select_type").val().toString()},
In PHP remove these lines :
foreach ($_POST as $key => $value) {
$_POST[$key] = trim(preg_replace('/\s+/', ' ', ($value)));
}
$arr_val = $_POST;
$loc = $arr_val['loc'];
$action = $arr_val['action'];
And these lines instead:
$loc = $_POST['loc'];
$action = $_POST['action'];
$loc =explode(","$loc );
foreach($loc AS $val)
{
echo $val; // your locations
}
<script>
function buttonClick(){
var total = 0;
var type = "";
for(var i=1;i<=3;i++) {
var id = "max_clicks" + i;
var label = "label" + i;
var badge = "badge" + i;
if (document.getElementById(id).checked!=null && document.getElementById(id).checked==true) {
total += parseInt(document.getElementById(id).value);
type +="Max-clicks:<hr style='margin-top:-1px;' />"+ "<span class='badge' style='margin-top:-5px;'>" + document.getElementById("label"+i).innerHTML + "</span> : <span class='badge' style='margin-top:-5px;'>" + document.getElementById("badge"+i).innerHTML + "</span><br />";
}
}
document.getElementById('Totalcost').innerHTML = total;
document.getElementById('individual').innerHTML = type;
}
</script>
<form action="<?php echo "".site_url."";?>/magaza/reklam-ver" method="post" enctype="multipart/form-data">
<input type="checkbox" name="max_clicks[]" id="max_clicks1" value="<?php echo "".$price1."";?>" onClick="buttonClick(this);">
<label id="label1" class="badge" style="background:#fc5a5d;"> 150 clicks</label>-<span class="badge" id="badge1">Price: 5 credits</span><br />
<input type="checkbox" name="max_clicks[]" id="max_clicks2" value="<?php echo "".$price2."";?>" onClick="buttonClick(this);">
<label id="label2" class="badge" style="background:#fc5a5d;"> 400 clicks</label>-<span class="badge" id="badge2">Price: 13 credits</span><br />
<input type="checkbox" name="max_clicks[]" id="max_clicks3" value="<?php echo "".$price3."";?>" onClick="buttonClick(this);">
<label id="label3" class="badge" style="background:#fc5a5d;"> 735 clicks</label>-<span class="badge" id="badge3">Price: 9 credits</span><br />
<span id="individual" class="badge" style="background:#f29d9d;">You dont have any select item.</span>
<button type="button"class="btn btn-primary" onclick="buttonClick()">Price to pay:
<span class="badge"><span id="Totalcost">0</span> credits</span></button>
<input class="btn btn-success" style="float:right;" type="submit" name="add_ad" value="Reklam satın al">
</form>
I trying to get checked item and send to mysql... All working but have problem with send to mysql i want to send max-click -info of <span>....</span> and check price with input value and send this to mysql - max-clicks -value off <span>..</span> and value of input any ideas ? i give my script form.php and action_form.php and sorry for my language :/
if($_POST['add_ad'])
{
if(!empty($_POST['max_clicks'])) {
$shipping_subtotal = 0;
foreach($_POST['max_clicks'] as $shipping){
$shipping_subtotal += $shipping;
}
$user = userInfo();
if($user['credits'] >= $shipping_subtotal){ //check user have enough credits or not
if($_POST['title'] && $_POST['target_url'])
{
$expires = strtotime("+1 month"); //Reklam 1 ay ekle
$title = quote_smart($_POST['title']);
$target_url = quote_smart($_POST['target_url']);
mysql_query("INSERT INTO ads (date_added,date_expires, target_url, clicks, author_id, title, max_clicks) VALUES ('".time()."',$expires, $target_url, '0', '".$_COOKIE['user_id']."', $title, $shipping_subtotal)") or die(mysql_error());
echo info("Success!");
delcredits($user['id'], $shipping_subtotal);
header ("refresh:3;url=".site_url."/magaza/reklam-ver");
}
else
{
echo error("Error.");
}
}
else
{
echo error("you dont have enough credits");
}
}
else{
echo "<b>Please select max-clicks.</b>";
}
}
This is weirding me out quite a bit...
If i delete the update statement it dont update the "views" at all... which makes sence.
If i delete the "Delete html" and run the file it will update once and not twice as it should? which does not make sense at all
How is this even possible, especially when there only are one update query and when it is plain HTML that needs to be deleted?
If anyone is interested i am prepared to do teamviewer if you do not belive me.
This is the sample page
All of the code seperated in blocks for readability
$stmt = $dbCon->prepare("SELECT id, views, rating, votes FROM rating ORDER BY id DESC LIMIT 1");
$stmt->execute();
$stmt->bind_result($id, $views, $rating, $votes);
$stmt->fetch();
$stmt->close();
$average = averageRate($rating, $votes);
$string1;
$string1 .= "<p>Id = " . $id . "</p><br>";
$string1 .= "<p>Views = " . $views . "</p><br>";
$string1 .= "<p>Rating = " . $rating . "</p><br>";
$string1 .= "<p>Votes = " . $votes . "</p><br>";
$string1 .= "<p>Average = " . averageRate($rating, $votes) . "</p><br><br>";
The update query
//THIS IS THE UPDATE QUERY PROBLEM
//UPDATERE DATABASED
$stmt = $dbCon->prepare("UPDATE rating SET
views = views + 1 WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
Delete HTML (If i delete this HTML the SQL updates once, weird right? the JS is whats used with that HTML)
<div class="topNav">
<span class="topNavArrow">
</span>
<div class="categoryWrapper">
<div id="categoryParent">
<input id="category01" class="categorys" type="checkbox" value="1" checked>
<input id="category02" class="categorys" type="checkbox" value="2" checked>
<input id="category03" class="categorys" type="checkbox" value="3" checked>
</div>
<label for="category01">
<img src="#" alt="category 01">
</label>
<label for="category02">
<img src="#" alt="category 02">
</label>
<label for="category03">
<img src="#" alt="category 03">
</label>
</div>
</div>
<script>
document.querySelector("#categoryParent").addEventListener("click", checkedCategory, false);
var categorys = document.getElementsByClassName("categorys");
var categorysLength = categorys.length;
var checked = "1,2,3";
function checkedCategory(e) {
checked = "";
for (var c = 0; c < categorysLength; c++) {
if (checked) {
var separator = ",";
} else {
var separator = "";
}
if (categorys[c].checked) {
checked += separator + categorys[c].value;
}
}
alert(checked);
e.stopPropagation();
}
</script>
The rest of the HTML
<div id="contentWrapper" class="contentWrapper">
<?php echo $string1;?>
<div class="contentInner">
<div class="contentHelper">
<div class="contentInfo">
<p id="contentViews">Views: <?php echo $views; ?></p>
<p>Votes: <?php echo $votes; ?> </p>
<p>Average: <?php echo $average; ?>/5</p>
<p class="<?php echo $voteYesNo; ?>"><?php echo $voteText ?></p>
</div>
<div class="contentImg">
</div>
</div>
</div>
</div>
Searched STO but i could not find any questions that covered my problem but some similair like this link
And no this is not a bad joke it is really whats going on...
I am new to Angular and am struggling to add a comment to a specific post that is being displayed from a database.
Under the post I have a hidden comment area that shows when pressing the button.
I then want to be able to add the comment to the post the comment area is attached too.
It seems like it is not getting the id but I can't find how to solve it.
It is doing the show/hide, and I am getting the "data inserted" in the console log so I'm guessing the problem is with the PHP?
Angular code
app.controller('meetings', function($scope, $http) {
$scope.meetings_insertdata = function() {
$http.post ("meetings_insert.php",{'meetings_commentdate':$scope.meetings_commentdate,'meetings_comment':$scope.meetings_comment})
window.location.reload();
console.log("data inserted");
};
});
app.controller('show_hide', function ($scope) {
$scope.Hidden = true;
$scope.ShowHide = function () {
$scope.Hidden = $scope.Hidden ? false : true;
}
});
meetings_insert.php
<?php
$data = json_decode(file_get_contents("php://input"));
$meetings_comment = $data->meetings_comment;
$meetings_commentdate = date('Y-m-d H:i:s');
$meetings_entry = $_GET['id'];
mysql_connect("localhost","user","password");
mysql_select_db("mdb_rh316");
mysql_query("UPDATE project_meetings SET (meetings_comment, meetings_commentdate) = ('$meetings_comment','$meetings_commentdate') WHERE meetings_entry = '$meetings_entry'");
?>
HTML code
<div class="entrybox" ng-controller="meetings">
<?php
mysql_connect("localhost","user","password");
mysql_select_db("mdb_rh316");
$result = mysql_query("SELECT * FROM project_meetings ORDER BY meetings_date DESC");
while ($row = mysql_fetch_array($result))
{
echo "<table>";
echo "<tr><td>" ?>Added: <? echo $row['meetings_date'] . $row['meetings_entry'] . "<br/>" . $row['meetings_content']."</td></tr>";
echo "<tr><td>" ?><br/><span class="emp">Comment: <?
echo $row['meetings_commentdate']."<br/>" . $row['meetings_comment']."</td></tr>";
echo "<tr><td>"?></span>
<div ng-controller="show_hide">
<input type="button" class="previous_add" value="Add comment" ng-click="ShowHide()" />
<br />
<br />
<div ng-hide = "Hidden">
<form method="post" action="meetings_insert.php?id=<? echo $row['$meetings_entry']?>">
<textarea class="textarea" placeholder="Add your comment here.." type="text" ng-model="meetings_comment" name="meetings_comment"></textarea><br/>
<input type="button" class="button" value= "Add" ng-click="meetings_insertdata()"/>
</form>
</div>
</div>
</td></tr><br/><?;
}
echo "</table>";
?>
</div>
Pass 'id' into the meetings_insertdata function:
<form method="post" action="">
<textarea class="textarea" placeholder="Add your comment here.." type="text" ng-model="meetings_comment" name="meetings_comment"></textarea>
<br/>
<input type="button" class="button" value="Add" ng-click="meetings_insertdata(<? echo $row['$meetings_entry']?>)" />
</form>
Receive it in the AngularJS function below:
app.controller('meetings', function($scope, $http) {
$scope.meetings_insertdata = function(id) {
$http.post("meetings_insert.php", {
'meetings_commentdate': $scope.meetings_commentdate,
'meetings_comment': $scope.meetings_comment,
'meetings_event': id
})
window.location.reload();
console.log("data inserted");
};
});
Then, pick up 'id' from the posted value ($data->meetings_event)
$data = json_decode(file_get_contents("php://input"));
$meetings_comment = $data->meetings_comment;
$meetings_commentdate = date('Y-m-d H:i:s');
$meetings_entry = $data->meetings_event;
I'm trying to make a paginating blog using PHP, HTML, and MySQL. I wrote the code but for some reason the webpage shows up blank. What's wrong with my code? Chrome's console returns a 500 internal server error.
<div id="article">
<?php
include 'php/mysql_connect.php';
if(empty($_GET)){
$current_id = SELECT max(id) FROM posts;
}
else{
$current_id = mysql_safe_string($_GET['id']);
}
$result = mysql_safe_query('SELECT * FROM posts WHERE id=%s LIMIT 1',$current_id);
if(!mysql_num_rows($result)){
echo '<h2>No Posts Found</h2>';
exit;
}
$row = mysql_fetch_assoc($result)
echo '<h2>'.$row['title'].'</h2>';
echo '<div class="row">';
echo ' <div class="group1 col-sm-6 col-md-6">';
echo ' <span class="glyphicon glyphicon-pencil"></span><a data-toggle="collapse" data-target="#comments" class"collapsed">'.$row['num_comments'].' Comments </a>';
echo ' <span class="glyphicon glyphicon-time"></span>'.date('F j<\s\up>S</\s\up>, Y', $row['date']);
echo ' </div>';
echo '</div>';
echo '<br />';
echo '<p class="lead">'.n12br($row['body']).'</p>';
?>
<div id="comments" class="collapse" >
<div class="well">
<h4>Leave a comment</h4>
<?php echo '<form role="form" method="post" action="php/comment_add.php?id=($current_id)" class="clearfix">'; ?>
<div class="col-md-6 form-group">
<label class="sr-only" for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" required />
</div>
<div class="col-md-6 form-group">
<label class="sr-only" for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" required />
</div>
<div class="col-md-12 form-group">
<label class="sr-only" for="content">Comment</label>
<textarea class="form-control" id="content" placeholder="Comment" required></textarea>
</div>
<div class="col-md-12 form-group text-right">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<br>
<?php
$result = mysql_safe_query('SELECT * FROM comments WHERE post_id=%s ORDER BY date ASC',$current_id);
echo ' <ul id="comments" class="comments">';
while($row = mysql_fetch_assoc($result)){
echo ' <li class="comment">';
echo ' <div id="inline" ><h4 style="display:inline;">'.$row['name'].'</h1><sup><p style="display:inline; font-size:10px;"> '.date('j-M-Y g:ia', $row['date']).'</p></sup></div>';
echo ' <em>'.n12br($row['content']).'</em>';
echo ' </li>';
echo ' </ul>';
}
?>
<hr>
</div>
</div>
<nav>
<ul class="pager">
<?php
$newer_id = IFNULL(mysql_safe_query('SELECT min(id) FROM posts WHERE id > $current_id ORDER BY id ASC LIMIT 1'),-1);
$older_id = IFNULL (mysql_safe_query('SELECT max(id) FROM posts WHERE id < $current_id ORDER BY id ASC LIMIT 1'),-1);
if($newer_id != -1){
echo '<li>Newer</li>';
}
if ($older_id != -1){
echo '<li>Older</li>';
}
?>
</ul>
</nav>
This is php/mysql_connect.php, which is supposed to prevent sql injection (i got this from a tutorial):
<?php
// mysql.php
function mysql_safe_string($value) {
$value = trim($value);
if(empty($value)) return 'NULL';
elseif(is_numeric($value)) return $value;
else return "'".mysql_real_escape_string($value)."'";
}
function mysql_safe_query($query) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
return mysql_query(vsprintf($query,$args));
}
function redirect($uri) {
header('location:'.$uri);
exit;
}
mysql_connect('localhost','(username)','(password)');
mysql_select_db('(database)');
From the logs I locate the failure which is:
Syntax error, unexpected 'max' (T_STRING) on line 6 (if(empty($_GET)){$current_id = SELECT max(id) FROM posts})
As other pointed out (and it should be immediately clear by the syntax error you are facing), your $current_id query is not being quoted. A good beginning is to fix the first block as such:
if(empty($_GET)) {
$current_id = "SELECT max(id) FROM posts;";
} else {
$current_id = mysql_safe_string($_GET['id']);
}
if(empty($_GET)){
$current_id = SELECT max(id) FROM posts;
}
no quotes around the sql is a mistake.
If your file is myfile.html and you don't have permission for embedded PHP it will not execute on the server.