Why is my php/mysql update not accurate? - php

I have a webpage with a button on it. When the button it clicked it sends a request to a page with this code on it
$userName = "tdscott";
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$divID = explode('?', $url);
$id = 0;
$id = explode('#',$divID[1])[1];
$func = $divID[2];
$find = mysqli_fetch_array(mysqli_query($con,"SELECT likes FROM status WHERE id='$id'"))['likes'];
if ($func == "addLike")
{
$promoted = $userName . "-";
mysqli_query($con, "UPDATE status SET promotedBy = CONCAT(promotedBy,'$promoted') WHERE id='$id'");
$find++;
mysqli_query($con,"UPDATE status SET likes = '$find' WHERE id='$id'");
echo $find;
}//end if addLike
elseif($func === "removeLike")
{
echo "ERROR";
}//end if removeLike
elseif ($func === "getLikes")
{
echo $find;
}//end if getLikes
mysqli_close($con);
I left of the database connection information. But for some reason when this is called it produces inaccurate results. For example... Sometimes it will put multiple instances of $promoted in the promotedBy field in my table and sometimes it will update other rows in the table that the id does not equal the current $id. I am wondering if somehow it is getting the $id variable mixed up from when I submitted it with a different value before. Is there a way to reset the variables before I call it each time?
Please note: In the if statement, we are only looking at the addLike portion. I included the other just in case it was causing the problem.

unset($id);
Sorry should have done more research.

Related

Printing single result from db2 query in php

I'm running a query on db2 in a php script, which is running successfully but I can't get it to echo the actual ID of the record I've selected. It does echo my success statement showing it ran successfully but I need the actual sessionid for comparison in another query.
Here I'm selecting the record, executing the query and checking for execution, but I'm also trying to use fetch_row and result to return the single selected ID:
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);
while(odbc_fetch_row($executeSessionMax)){
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
}
How can I return the sessionID into a variable properly from db2?
You are passing the wrong parameter to the odbc_fetch_row() as $executeSessionMax is either a True or False depending on successful execution.
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);
while(odbc_fetch_row($prepareSessionMax )){
// correction here ^^^^^^^^^^^^^^^^^^
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
}
You could recode as this specially as a MAX() will only ever return one row so the while loop is not needed either.
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
if (odbc_execute($prepareSessionMax)) {
odbc_fetch_row($prepareSessionMax );
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
// if echo gets lost try writing to a file
error_log("maxResult = $maxResult", 3, "my-errors.log");
} else {
// something went wrong in the execute
}
You could also try
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$result = odbc_exec($DB2Conn, $latest_result);
$rows = odbc_fetch_object($result);
echo $row->SESSIONID;
$maxResult = $row->SESSIONID;

PHP Array to string to mysql - empty record

I am on point where I have to usk on forum.
So, I have an array that is my return from join table sql query.
i am displaying it correctly without the problem.
but some of those values I want to put in different table of mysql database.
$array = joint_table();
$array_value = array['key'];
I can echo array_value and it's displaying correctly, also checked variable type and it returns STRING.
however when I am inserting it into the table, it's empty cell.
I am inserting other stuff like date() and such and that is inserted correctly.
So my sql query works fine, besides I am using same query in other places without problem.
Only values I have from that array are not inserting, but still can echo them.
<?php
$page_title = 'Complete Task';
require_once('includes/load.php');
// Checkin What level user has permission to view this page
page_require_level(2);
$task = join_task_table((int)$_GET['id']);
?>
<?php
if(isset($_POST['complete_task'])){
$area = $task['area'] ;
$jig = $task['jig'];
$desc = $task['description'];
$freq = $task['freq'];
$date = make_date();
$user = current_user();
$user_done = remove_junk(ucfirst($user['name']));
$comment = remove_junk($db->escape($_POST['comment']));
if(empty($errors)){
$sql = "INSERT INTO tpm_history (area_name,jig_name,description,frequency,date_done,done_by_user,comment)";
$sql .= " VALUES ('{$area}','{$jig}','{$desc}','{$freq}','{$date}','{$user_done}','{$comment}')";
$result = $db->query($sql);
if($result && $db->affected_rows() === 1){
$session->msg('s',"Job Completed");
redirect('home.php', false);
} else {
$session->msg('d',' Sorry failed to complete the task!');
redirect('task_complete.php?id='.$task['id'], false);
}
} else{
$session->msg("d", $errors);
redirect('task_complete.php?id='.$task['id'],false);
}
}
?>
I am lost. Help.

passing a php variable in $_POST

i have a question regarding passing a php variable in the $_POST knowing that i named my buttons using the same variable because i want the buttons to have unique names.
while($row = mysql_fetch_array($query)){
$friend_id = $row['friend_id'];
$result = mysql_query("SELECT username FROM users WHERE user_id = '$friend_id'");
if (mysql_num_rows($result) > 0) {
$friendname = mysql_result($result,0,"username");
$friendname = sanitize($friendname);
echo '<input type = "submit" id='. $friend_id .' name ='.$friend_id.' class = "member" value ='. $friendname.' /><br>';
}
here where i am trying to pass it but it is not working
print_r($_POST);
if(isset($_POST['name'])){
$signers = mysql_query("SELECT friend_id FROM friends WHERE user_id = $session_user_id ");
$count = mysql_num_rows($signers);
if($count == 0){
echo "<p>you need to add team members</p>";
}
else{
while($row = mysql_fetch_array($signers)){
$signer_id .= $row['friend_id'];
}
echo '<p>'.$signer_id . '</p>';
}
$request = mysql_query("INSERT INTO requests VALUES ('','$user_id','$fid','$fname','$signer_id')");
}
else {
echo '<p> not working </p>';
}
both of those sections are in the same php page
You're not passing a variable around, you're passing a value so this line -
if(isset($_POST["'$friend_id'"])=== true){
needs to be changed to this -
if(isset($_POST['name'])){
The name attribute (along with the value) of each input is what is passed in a POST. You're just checking to see if the name parameter has a value, if it does then you can act on it with other code.
In addition please stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO.
The condition in the second piece of code should be without quotes:
if (isset($_POST[$friend_id])) {...
The part === true isn't necessary in this case, I've removed it.
You should look into predefining any variables you intend to use.
function input_post ($value, $default) {
return isset($_POST[$value]) ? $_POST['value'] : false;
}
Then use the post as so, this would prevent any not set errors
$friend_id = input_post('friend_id');
if ($friend_id) {
// If friend_id is set, do this
}
else {
// If friend_id is false or unset
}

ajax returns success but mysql db not updated

I have a javascript for loop that sends an array to an ajax page to update the mysql database.
I echo the result back to the original page and it echos as a success but when I check the db nothing has changed
my javascript for loop that sends the array
for(var m=0; m<array.length; m++){
$.post("update_page_positions.php",{page_ref:array[m][0], ref:array[m][12], menu_pos:array[m][1], sub_menu_pos:array[m][2], top_menu:array[m][3], pagelink:array[m][4], indexpage:array[m][5], hidden:array[m][6], page_title:array[m][7], page_desc:array[m][8], page_keywords:array[m][9], page_name:array[m][10], deletedpage:array[m][11]},
function(data,status){
alert("data="+data+" status="+status);
});
here is the php ajax page the updates the db
<?
include("connect.php");
$ref = $_POST['ref'];
$page_ref = $_POST['page_ref'];
$menu_pos = $_POST['menu_pos'];
$sub_menu_pos = $_POST['sub_menu_pos'];
$top_menu = $_POST['top_menu'];
$indexpage = $_POST['indexpage'];
$page_name = $_POST['page_name'];
$page_title = $_POST['page_title'];
$page_desc = $_POST['page_desc'];
$page_keywords = $_POST['page_keywords'];
$hidden = $_POST['hidden'];
$pagelink = $_POST['pagelink'];
$deletedpage = $_POST['deletedpage'];
$query = mysql_query("SELECT * FROM pages WHERE ref='$ref' AND page_ref='$page_ref'");
if(mysql_num_rows($query)==0){
mysql_query("INSERT INTO pages(page_ref, ref, page_name, menu_pos, sub_menu_pos, top_menu, link, indexpage) VALUES('$page_ref','$ref','$page_name','$menu_pos','$sub_menu_pos','$top_menu','$pagelink','$indexpage')");
}
if($deletedpage=="1"){
mysql_query("DELETE FROM pages WHERE ref='$ref' AND page_ref='$page_ref'");
mysql_query("DELETE FROM site_content WHERE ref='$ref' AND page_ref='$page_ref'");
}
else{
if(mysql_query("UPDATE pages SET menu_pos='$menu_pos', sub_menu_pos='$sub_menu_pos', top_menu='$top_menu', indexpage='$indexpage', page_name='$page_name', page_title='$page_title', desc1='$page_desc', keywords_list='$page_keywords', hidden='$hidden', link='$pagelink' WHERE ref='$ref' AND page_ref='$page_ref'")){
echo "updated!";
} else{
echo "error";
}
}
?>
the INSERT and DELETE functions are fine but the UPDATE returns a success statement but does not update the db.
Can anyone see what the problem is?
Posted as an answer because the comment was too hard to read:
Rather than echoing "updated", try echoing
"UPDATE pages SET menu_pos='$menu_pos', sub_menu_pos='$sub_menu_pos', top_menu='$top_menu', indexpage='$indexpage', page_name='$page_name', page_title='$page_title', desc1='$page_desc', keywords_list='$page_keywords', hidden='$hidden', link='$pagelink' WHERE ref='$ref' AND page_ref='$page_ref'"
(ie. the query you're trying to run).
See if that gives you some clues.
UPDATE reports success, but does nothing in case when its WHERE clause rejects all rows in updated table.
Maybe $page_ref identifier is correct (so DELETE works), but full $page_ref and $ref combination is not?

table updates empty spaces when user do not enter anything to the textbox

i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.

Categories