it is not inserting correct values in db? - php

I want to insert a sessionid and a set of students into the db.
The sessionid can be found in line of code below:
<td><input type='hidden' id='currentId' name='Idcurrent' readonly='readonly' value='4' /> </td>
A set of students are displayed in a select box as so:
<select id="studentadd" name="addtextarea">
<option value='1'>u08743 - Joe Cann</option>
<option value='4'>u03043 - Jill Sanderson</option>
<option value='7'>u08343 - Craig Moon</option>
</select>
Now I am using ajax to get both the sessionId value and the student's value and post them into a seperate php page where the insert happens by using code below:
function submitform() {
$.ajax({
type: "POST",
url: "updatestudentsession.php",
data: {
Idcurrent: $('#currentid').val(),
addtextarea:$('#studentadd').val()
},
dataType:'json', //get response as json
success: function(result){
if(result.errorflag){
$("#targetdiv").html('success');
}else{
//you got success message
$("#targetdiv").html('error');
$('#targetdiv').show();
}
}
});
}
Below is the seperate php file updatestudentsession.php where it is suppose to do the insert:
$studentid = array();
$studentid[] = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : '';
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : '';
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
}
$insert->close();
Now the problem I am having is that is not inserting the correct data in at all. It is insert the value 0 in both the SessionId and StudentId fields. Below is what the table should look like after the insert:
SessionId StudentId
4 1
4 4
4 7
Instead it looks like below:
SessionId StudentId
0 0
My question is what is causing it to not be able to retrieve and insert the correct data into the db?

Suppose part of problem is here:
Idcurrent: $('#currentid').val(),
In your HTML code ID is currentId when you are trying to get an element with id currentid. id selector is case sensitive. So, you simply pass nothing to your PHP as jquery can't find an element.
Not sure what is wrong with $studentid, but I see no reason to use an array there as you always pass only one value, so try to change your php code like below:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : '';
//var_dump($studentid);
//var_dump($sessionid);
//var_dump($_POST); - this is additionally to see whole $_POST variable.
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
}
$insert->close();
Also, see at commented out var_dump lines at the beginning. They will print values of your variables so you will be able to see what is actually set there. (as it is ajax, you will need to open developer tools and see what is returned in result on network tab)
UPD:
According to the latest comment, appears that$_POST['addtextarea'] is an array. Because of that code is modified to handle that. Please note how that value is taken:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
Old code, which is:
$studentid = array();
$studentid[] = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : '';
results in two level array. So $studentid is an array which contains one element which is an array also. That is why old for each loop is not working. $id were an array. And it was converted to 0

I think there is a probel in data :
data: {
Idcurrent: $('#currentid').val(),
addtextarea:$('#studentadd').val()
},
Try :
data: {
"Idcurrent": $('#currentid').val(),
"addtextarea":$('#studentadd').val()
},
Please not the double quotes "Idcurrent"

Related

Updating Mysql database data using Php and Ajax

I'm trying to set up a button which when clicked adds a fixed number to the database value. The database is called var_stat and consists of id and value. The table has one row so far where id = var and value = 35. If clicked, the button should add 5 to the value making it 40.
I'm not sure what to do here, as all answers I found used a completely different approach and strings instead of integers. So far I have done this:
if (isset($_POST['n'])){
$n = $_POST['n'] ;
$stmt = $con->prepare('UPDATE var_stat SET value = value + $n WHERE id = ? ');
$stmt->bind_param('s', $id);
$id = "var";
$stmt->execute();
$stmt->close();
}
<script src="js/jQuery-3.4.1.js"></script>
<script>
function add(n){
$.ajax({
type: "POST",
url: "update.php",
data: {
'n' : n
},
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
<form>
<input type="button" value="+5" class="btn btn-circle btn-grey col-sm-10" onclick="add(5);">
</form>
If I change $n in the update.php to an integer and run the update.php by itself it works, however I can't seem to get this to run through my html page, so I guess there's something wrong with my javascript code?
Bind the n as well, move the id before the binding statement
if (isset($_POST['n'])){
$n = $_POST['n'] ;
$id = "var";
$stmt = $con->prepare('UPDATE var_stat SET value = value + ? WHERE id = ? ');
$stmt->bind_param('is',$n, $id);
$stmt->execute();
$stmt->close();
}

Inserting multiple rows with jQuery, PHP and MySQL using arrays

I know this has been asked a million times, but I just can't seem to get it right. I am trying to insert multiple rows at the same time with data sent using jQuery.
I am using AJAX/jQuery to send values like this:
jQuery / AJAX
var extrasids = $('.classextrasid').map(function() {return $(this).val()}).toArray();
var extrasrates = $('.classextrasid').map(function() {return $(this).data('rates')}).toArray();
var extrasquantities = $('.classextrasid').map(function() {return $(this).data('quantity')}).toArray();
$.ajax({
type: "POST",
url: "modules/addsinglebooking.php",
dataType: 'json',
data: {extrasids:extrasids,extrasrates:extrasrates,extrasquantities:extrasquantities},
cache: false,
})
My PHP looks like this:
PHP
<?php
session_start();
$inputvalues = $_POST;
$errors = false;
$returnResult;
$result = false;
include_once '../../includes/database.php';
$extraids = $inputvalues['extrasids'];
$extrarates = $inputvalues['extrasrates'];
$extraquantities = $inputvalues['extrasquantities'];
if( !$errors ) {
foreach($extraids as $extraid){
$stmt = $mysqli->prepare("INSERT INTO `extras`(`extraid`,`extrarate`,`extraquantity`) values (?,?,?)");
$stmt->bind_param('sss', $extraid,$extrarates,$extraquantities);
if(!$stmt->execute()) echo $stmt->error;
}
$result = $stmt->get_result();
$returnResult = "Success";
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
My problem:
If my values looked like this, my above code would work:
extraid extrarates extraquantity
---------------------------------------
1 rate1 quantity1
2 rate1 quantity1
3 rate1 quantity1
but all values are different like this:
extraid extrarates extraquantity
---------------------------------------
1 rate1 quantity1
2 rate2 quantity2
3 rate3 quantity3
So I only to loop through one array and add multiple records if the rest of the values are the same and only one value is different.
How can I loop through everything to add 3 multiple rows which are unique?
In your foreach you can add this:
$i = 0;
foreach($extraids as $extraid){
$stmt = $mysqli->prepare("INSERT INTO `extras`(`extraid`,`extrarate`,`extraquantity`) values (?,?,?)");
$stmt->bind_param('sss', $extraid,$extrarates[$i++],$extraquantities[$i++]);
if(!$stmt->execute()) echo $stmt->error;
}
So first setting $i to 0 and then in the loop increment it with each time it repeats

Finding a match between array and database

I have an array called "selected_checkboxes". In my database I have multiple columns and some of them contain the value 1, otherwise the value will be NULL. The names of those columns are exactly the same as the values of the array.
I would now like to check dynamically if the values of my array ($_POST['selected_checkboxes']) match with the values of my columns in the database. If ALL values from the array have the value 1 in the database, it should echo something like Match!
This is what I have tried so far but I think it's completely wrong:
if(!$result = $db->query("SELECT * FROM products")){
die('Error');
}
while($row = $result->fetch_object()){
foreach($_POST['selected_checkboxes'] as $value) {
if ($value == 1) {
$say .= $value . ' is = 1';
}
}
}
echo $say;
I appreciate any help!!
Edit:
This is how the array 'selected_checkboxes' is getting generated:
$('.show_result').click(function() {
// Get all selected checkboxes
var selected = [];
$.each($("input[type=checkbox]:checked"), function(){
selected.push($(this).attr('id'));
});
// Get the selected option field
selected.push($('#PG_Select_Bereich1').val());
// Deliver data to PHP
$.ajax({
url : "typo3conf/ext/produkteguide_sg/pi1/products.php",
type: "POST",
data : { selected_checkboxes:selected },
success: function(data, textStatus, jqXHR)
{
$("#PG_Resultate").html(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
//alert(errorThrown);
}
});
And this is how my database looks like:
I've done something similar but in a different way, I hope this is what you're looking for:
// Query execution
$result = mysqli_query($CONN,"SELECT * FROM whatever");
while($row_from_db = mysqli_fetch_array($result)){
$db_value = is_null($row_from_db['myValue']) ? 0 : 1;
$check_value = !isset($_POST['selected_checkboxes']['myValue']) ? 0 : 1
echo $db_value == $check_value ? "Match!" : "Not matching :(";
}
I am writing pseudo code for your requirement.
1) loop through array.
2) while loop through array if value of element is found 1 the go to next step otherwise continue loop.
3) If array element value is 1 then get a key of element and prepare sql query which checks that column name same as key name have value as 1 for each record then mark it as Match.
Hope this helps to you. If you not get with this then let me know i will write the code for you.
Edit:
Each of your checkbox name must be same as column name in database.
$array_checkbox = $_POST['selected_checkboxes'];
$query =" SELECT count(*) FROM <tabel_name> WHERE 1=1";
// get count from query and store it in $total_rows variable
$total_rows = 10; // for example purpose we take count value as 10
foreach($array_checkbox as $key => $checkbox){
$query = $query =" SELECT count(*) FROM <tabel_name> WHERE $key=1"; // here we take key of array as column name in sql query and getting that how many rows of the column have value 1
// get count from query and store it in $result variable
$result = 10;
if($result == $total_rows){
echo "Match";
}
}
Hope this is according to your requirement.

How to update mysql database fields in groups (using GROUP BY)

I have a table named youi in my database. All fields in the table already contain values except for the aff and desc fields. See image below.
Now, I have a form in my HTML page (See image below) where I want to update the desc and aff fields according to their camp. I have not yet dealt with this kind of setup before. I've been thinking how to do this for almost a day now but still can't seem to find a perfect solution. Could you give me ideas or solutions on how to achieve this? I'm using PHP and mySQL.
Thanks in advance!
The easiest way i see is using a different UPDATE for each of those lines.
You could do that in a loop in php where you construct your update with the values of aff, desc and campaign for each line.
The sql would be:
UPDATE tableName
SET aff = varAffiliate,
desc = varDescription
WHERE campaign = varCampaign;
The php part i'm not of much help, sorry.
You can use CASE, WHEN and THEN in a loop to make the one query.
This is a statement I created using a simple for loop to update a bunch of captions on a group of photos.
UPDATE Images SET caption = CASE imgID WHEN 389 THEN 'a' WHEN 390 THEN 'sdf' WHEN 391 THEN 'safasasadf' WHEN 392 THEN 'fs' WHEN 393 THEN 'dfdsf' WHEN 394 THEN 'sfdf' END WHERE imgID IN (389,390,391,392,393,394);
Hope that helps
aff = (case when somefield='slkd' then yyy end),
desc = (case when somefield='slkdfdsd' then xxx end)
I finally found a solution to this problem. I used combination of jQuery, AJAX, PHP and mySQL for it to work.
All <select> have the same id. The same for <input> and <label>. Here's a sample of my HTML code:
<select id="youiaff">
<option>1001</option>
<option>1007</option>
<option>1009</option>
<option>1013</option>
<option>1017</option>
<option>1018</option>
<option>1022</option>
</select>
<input id="youidesc" type="text" />
<label id="youicamp"></label>
<button type='button' class='btn btn-success saveyouiid'>Save</button>
What I did next was to create a jQuery code that will get all the values of <select>, <input> & <label> and put each of them in an array. I used their ids as identifiers. Here's the code:
var desc = $("input[id='youidesc']")
.map(function(){return $(this).val();}).get();
var aff = $("select[id='youiaff']")
.map(function(){return $(this).val();}).get();
var camp = $("label[id='youicamp']")
.map(function(){return $(this).text();}).get();
Then, I passed the variables to the PHP script using AJAX:
$.ajax({
type: 'post',
url: 'saveyouiid.php',
data: {
desc:desc,
aff:aff,
camp:camp,
},
success:function(data){
}
});
This codes will be executed upon clicking the save button. So the full jQuery/AJAX for this would be:
$('.saveyouiid').click(function(){
var desc = $("input[id='youidesc']")
.map(function(){return $(this).val();}).get();
var aff = $("select[id='youiaff']")
.map(function(){return $(this).val();}).get();
var camp = $("label[id='youicamp']")
.map(function(){return $(this).text();}).get();
$.ajax({
type: 'post',
url: 'saveyouiid.php',
data: {
desc:desc,
aff:aff,
camp:camp,
},
success:function(data){
}
});
});
The PHP script (saveyouiid.php) will then accept the values sent via AJAX. These values are arrays. What I did next was I combined the arrays to form a multidimensional array. Then, I get the individual values and perform the mySQL query. Here's what the script looks like:
<?php
$con = mysqli_connect("localhost","imu_fryu","frankyouiIMU2013","imu_frankyoui");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$aff = $_POST['aff'];
$desc = $_POST['desc'];
$camp = $_POST['camp'];
$arr = array_map(null, $aff, $desc, $camp);
foreach($arr as $array)
{
$aff = $array[0];
if ($aff == ">> Select Affiliate ID <<"){
$affID = "0";
}else{
$affID = $aff;
}
$desc = $array[1];
$camp = $array[2];
$sql1 = "UPDATE youi SET aff = '$affID', descr = '$desc' WHERE camp = '$camp'";
if (!mysqli_query($con,$sql1)) {
die('Error: ' . mysqli_error($con));
}
}
mysqli_close($con);
?>
I hope this could help someone in the future. :)

Insert multiple values sent from AJAX into sql database

hi have this code which works perfectly with just value:
<script type="text/javascript">
$(document).ready(function() {
$("input[type=button]").click(function () {
var textarea_content = $('textarea#wall').val(); // get the content of what user typed (in textarea)
if (textarea_content != '') { // if textarea is not empty
var sender = "<?php echo $_SESSION['user_id'];?>";
$.ajax({
type: "POST",
url: "send_message_function.php",
data : "action=send&from_id="+sender+"&to_user="+$(this).siblings("input[type=text]").val()+"&message="+textarea_content,
dataType: "json",
success: function (data) {
var LastID = data["cid"];
alert("toUser: " + $(this).siblings("input[type=text]").val()+"and text area " + textarea_content + " message id: " + LastID);
}
});//end success function
//do something else
} else {
alert('Enter some text ! '); // just in case somebody click on share witout writing anything :)
}
});//end click function
});//end ready function
</script>
and send_message_function.php :
<?php
require 'core/functions/init.php';
$action = $_POST['action'];
if($action=="send"){
$from_id = mysql_real_escape_string($_POST['from_id']);
$to_id = mysql_real_escape_string($_POST['to_user']);
$message = strip_tags($_POST['message']);
$sql = mysql_query("INSERT INTO chat (from_id, to_id, message, dt)VALUES('$from_id','$to_id','$message',NOW())") or die("0");
echo json_encode(array("cid"=>(mysql_insert_id()),
"from_id"=>''.$message_id.''));
}
?>
the problem is when I try to send the message to multiple users. The sql query try to insert all the users IDs in the same row. I know I should do some loop but I can't think how run the query for every users I want to send the message to.
$(this).siblings("input[type=text]").val()
returns multiple users id like this: 113,143,234
you do not need a loop, you can do multiple inserts with just one query, like this:
$to_id = explode(',', mysql_real_escape_string($_POST['to_user'])); //split the string to an array containing each id
$sql = mysql_query("INSERT INTO chat (from_id, to_id, message, dt) VALUES('$from_id','$to_id[0]','$message',NOW()), ('$from_id','$to_id[1]','$message',NOW()), ('$from_id','$to_id[2]','$message',NOW()) ") or die("0");
Note: $from_id shouldn't be a primary key, else you would get a duplicate key error.
Edit: If you do not know the no. of users,
$to_id = explode(',', mysql_real_escape_string($_POST['to_user']));
foreach ($to_id as $v)
$sql = mysql_query("INSERT INTO chat (from_id, to_id, message, dt) VALUES('$from_id','$v','$message',NOW()) ") or die("0");
You need to split the users ids string in the comma character, then execute a query for each value founded.
To insert multiple rows in one SQL query, do this
INSERT INTO foo(a, b) VALUES('c', 'd'), ('e', 'f'), ('h', 'i');
You'll need to loop to build each VALUES set, but you can do the insert in a single query.
So something like
<?php
$to_id = explode(',', mysql_real_escape_string($_POST['to_user']));
$sql = 'INSERT INTO chat (from_id, to_id, message) VALUES';
foreach ($to_id as $id)
{
$sql .="('$from_id', '$id', '$message'),";
}
rtrim($sql, ','); //strip the final comma
?>
That should form a query along the lines of
INSERT INTO chat(from_id, to_id, message) VALUES('1', '2', 'hello from php'), ('1', '3', 'hello from php'), ('1', '4', 'hello from php')
Doing it this way means only a single query is sent: therefore there's less overhead on communicating with the database which will speed up your script.
$toIDS = explode(',', mysql_real_escape_string($_POST['to_user']));
foreach($toIDS as $ID){
$query=mysql_query("INSERT INTO foo(a, b) VALUES('c', 'd')");
echo (mysql_affected_rows()>0)?$ID .'INSERTED':$ID.' NOT INSERTED';
}

Categories