Error with UPDATE query not updating my MySql database - php

I am trying to pass an array of data to a Update query, to update customer records. However for some reason the ?success page is showing saying my details have been updated, however they aren't. If I debug and echo
echo implode(', ', $update);
die();
I get the result
mem_first_name = 'Josh', mem_last_name = 'smith', mem_email = 'j.smith#gmail.com', allow_email = '0'
Which looks fine to me. This is my update_user function
function update_user($mem_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `members` SET " . implode(', ', $update) . " WHERE `mem_id` = '$mem_id'") or die(mysql_error());
}
And my $update_data array
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
$message = 'Your details have been updated';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$update_data = array(
'mem_first_name' => $_POST['mem_first_name'],
'mem_last_name' => $_POST['mem_last_name'],
'mem_email' => $_POST['mem_email'],
'allow_email' => ($_POST['allow_email']) ? 1 : 0
);
update_user($session_member_id, $update_data);
header('Location: settings.php?success');
exit();
} else if (empty($errors) === false) {
$message = output_errors($errors);
}
}
So I have worked out I am losing my backticks after I implode, thus the column names don't have back ticks

This is some sort of typo (and thus not a real question of course).
You are adding backticks to your fields
$update[] = '`' . $field . '`
^ here
But they are absent in the debug out.
So, you are either run or post wrong code, which makes whole question pointless.

check connection with db, and table field name spells., i think no problem in this code.

Related

Why does this "if" statement get triggered?

I've been working for the past 5 hours on why does this if get triggered...
Let me show you the code and explain you :
<?php
require_once "ConnectDB.php";
$link2 = $link;
$key = $posthwid = "";
$err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["key"])){
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (1)";
}
else{
$key = trim($_POST["key"]);
}
$hwid = $_POST["hwid"];
if(empty($err)){
$sql = "SELECT hwid, idkey, length, created_at FROM money WHERE idkey = '" .$key. "'";
$row = mysqli_query($link, $sql);
if(mysqli_num_rows($row) < 2){
while($result = mysqli_fetch_assoc($row)) {
if($result["idkey"] == $key)
{
$err = "key";
if($result["hwid"] == "")
{
$err = "nohwid";
$sql2 = "UPDATE IceCold SET hwid = '" .$hwid. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)){
$hwid = $result["hwid"];
mysqli_close($link2);
echo "debug";
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
if ($hwid !== $result["hwid"]) {
$err = "Contact the support";
}
elseif($_SESSION["admin"] == true) {
//Do special stuff
}
else {
///do other checks
if($created_at > $date){
$err = $hwid;
} else {
$err = "The key date is too old, buy a new one.";
}
}
}
else{
$err = "The key you entered was not valid.";
}
} mysqli_close($link);
} else {
$err = "multiple entry, contact support";
}
}
} else {
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (3)";
}
echo $err;
?>
So basically, I have this Connect DB file with a mysqli_connect called $link and I'm designing a liscence API for my program. My program will send a request with the "idkey" and "hwid" and is waiting for the hwid to come back. I have an entry in my sql databse with only a key registered and I've trying to make my program wotk by generating POST request with the id and a random hwid but I've found no success. If variables are weirdly moved around, It's because of the debugging.
Right now, with my current setup, I get the Contact the support response which I don't understand why?!? The request and the key are correct if I'm able to get this awnser.
It's probably a stupid mistake but I jsut can't figure it out...
Thanks in advance for your help
Edit: the if statement I'm referring to is this:
if($hwid !== $result["hwid"])
There was a typo in the code that I fixed but it wasn't the issue,
as for the elseif, that would destroy the order of execution of the code and destroy the logic behind it(If that made sense).
Weirdly, after some tests, I found out that the second SQL request I send doesn't want to be executed ($sql2) and there is no error in httpd logs... Can you execute two requests? I tried to create $link2 but it doesn't change anything
EDIT : Found solution
if($result["hwid"] == "")
{
$sql2 = "UPDATE money SET hwid = '" .$_POST["hwid"]. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)) {
$newhwid = $_POST["hwid"];
mysqli_close($link2);
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
elseif ($_POST["hwid"] != $result["hwid"]) {
$err = "Contact the support";
}
if($_POST["hwid"] == $newhwid || $_POST["hwid"] == $result["hwid"] ) {
/// do other checks
}
The condition before that one, if($row['hwid'] = ""), is an assignment. This code is changing the value of $row['hwid'] to an empty string, causing the condition after it to be true. I assume you meant to write == to test if $row['hwid'] is empty; otherwise it doesn't make sense to write this as an if statement.
By the way, it's not clear whether this if statement shouldn't be an else if. The rest of the branches here are else if (or elseif, which is the same in PHP), so you should consider whether you have missed out an else on this one too.

Weird space appeared beside INSERT query in MYSQL using PHP

I have insert function, this function works fine in other page. It's really weird that when try to debug it I found out that there's a weird big enter space beside the INSERT
Like this
"
INSERT INTO table (`sample`) values ("sample")"
Other pages are working fine without enter space
"INSERT INTO table (`sample`) values ("sample")"
here's my function
function insertData($table_name = '', $postedData = array(), $header = '',
$debug = TRUE)
{
$keys = '';
$values = '';
if(!$table_name || !$postedData) {
exit('missing parameter');
}
if(count($postedData)) {
unset($postedData['insert']);
$sql = "INSERT INTO $table_name " . $this->arrayToQueryString($postedData);
if($debug) {
exit($sql);
}
$statement = $this->connection->prepare($sql);
if($statement->execute()) {
if($header != 'login') {
header('Location: ' . $header);
return TRUE;
}
}
}
return FALSE;
}
Thanks works fine in my Localhost but when I transferred it in cpanel server got this problem

Header is not working

My header is not working.
<?php
$name = mysql_prep($_POST['name']);
$pastor = mysql_prep($_POST['pastor']);
$head = mysql_prep($_POST['head']);
$schedule = mysql_prep($_POST['schedule']);
$venue = mysql_prep($_POST['venue']);
$id = mysql_prep($_GET['ministryid']);
$errors = array();
$required_field = array('name', 'pastor', 'address', 'schedule', 'venue');
foreach ($required_field as $fieldname) {
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$errors[] = $fieldname;
echo "Sorry, you missed to complete {$fieldname} <br />";
}
else {
$query = "UPDATE ministry SET
name = '{$name}',
pastor = '{$pastor}',
head = '{$head}',
schedule = '{$schedule}',
venue = '{$venue}'
WHERE id = {$id}";
mysql_query($query);
if(mysql_affected_rows() == 1) {
header('location: editministry.php?');
exit;
} else {
echo "Updating Failed on {$s_ministry['name']} <b />".mysql_error();
exit;
}
}
}
require_once("include/footer.php");
Every time I have successful update, the link change its address.
For example, when I'm updating id = 3, the address will change to editministry.php?ministryid=3.
You dont send anything along your URL, thats why your header won't work. Check for yourself.
if(mysql_affected_rows() == 1) {
header('location: editministry.php?');
exit;
Your link will become effectivly baseUrl/editministry.php?.It searches than for a variable, which is not defined. I am not sure how you actually can pass on a variable that you didnt define in a link, yet it sends you there. Don't know. But if you just tell it to the hard link without the questionmark, it should go to that page. For me it works at least within my code. For you it would be:
if(mysql_affected_rows() == 1) {
header('location: editministry.php' );
exit;
In my code it looks like this:
header( "Location: http://" . strip_tags( $_SERVER ['HTTP_HOST'] ) . "/newHolo/index.php" );

form save empty value php

I have created a profile page in php, where the user, using a form can save his telephone number in a table named profile in database. If the user decides to change his telephone number can easily go to form change it and save it again. My only problem is the following. Suppose that the user wants to delete his telephone number. If he goes to the form delete his number (makes the field empty) and press save , the telephone number doesn't change to an empty value and continues to keep the previous number. Any idea how to change this in order to keep an empty value?
This is my code with the form :
<form action="" method="POST" >
<?php
if ( isset($_GET['success']) === true && empty($_GET['success'])===true ){
echo'Profile Updated Sucessfuly';
}else{
if( empty($_POST) === false && empty($errors) === true ){
$update_data_profile = array('telephone' => $_POST['telephone']);
update_user_profile($session_user_id, $update_data_profile);
header('Location: profile_update.php?success');
exit();
}else if ( empty($errors) === false ){
echo output_errors($errors);
}
?>
Telephone<input name="telephone" type="text" size="25" value="<?php echo $user_data_profile['telephone']; ?>"/>
<input type="submit" value="" name="submit"/>
</form>
And this is my function that dispatches data to profile table:
function update_user_profile($user_id, $update_data_profile){
$result = mysql_query("select user_id from profile where user_id = $user_id limit 1");
if(mysql_num_rows($result) === 1){
$update = array();
array_walk($update_data_profile, 'array_sanitize');
foreach($update_data_profile as $field => $data ){
if(!empty($data)){
$update[]='`' . $field . '` = \'' . $data . '\'';
}
}
if(isset($update) && !empty($update)){
mysql_query(" UPDATE `profile` SET " . implode(', ', $update) . " WHERE `user_id` = $user_id ") or die(mysql_error());
}
}
else{
$user_id = $update_data_profile['user_id'] ;
if(count($update_data_profile)){
$columns = array();
$values = array();
foreach($update_data_profile as $field => $data){
$columns[] = $field;
$values[] = $data;
}
}
mysql_query(" INSERT INTO `profile` (" . implode(",", $columns) .") values ('" . implode("','", $values) . "')" ) or die (mysql_error());
}
}
You are only updating the field if the data is NOT empty.
See this line:
if(!empty($data)){
Because you're explicitly ignoring empty values with this:
if(!empty($data))
Since empty() function can validate for missing, and false elements, you can't simply pass that on to a SQL query. So, if you want to actually generate a query for these items, you will need to set the value explicitly by doing something like this:
if (empty($data)) {
$update[] = "`{$field}` = ''" ;
} else {
$update[] = "`{$field}` = '{$data}'" ;
}
If you are writing for PHP 5.3 or above, you could also replace the if..else statement and shorten your code by using a ternary operator (conditional assignment) doing something like this:
$update[] = (empty($data)) ? "`{$field}` = ''" : "`{$field}` = '{$data}'";

updating data in mysql database using arrays

I would like to update information that is already in the database, but using an array. I get 'successfully update' message white the data in the database is not updated.
the following is the function I use to do the insertion:
function update_knowledge_modules($update_data,$value)
{
$update = array();
array_walk($update_data,'array_clean');
foreach($update_data as $field=>$data)
{
$update[] = '.$field. = \''.$data.'\'';
}
$query = "UPDATE knowledge_modules SET".implode(', ',$update)."WHERE curr_code =$value";
mysql_query($query)
or die(mysql_error);
}
<?php
if(isset($_GET['success']) == true && empty($_GET['success'])==true)
{
echo 'Changed successfully';
}
else
{
if(empty($_POST)== false && empty($errors)== true )
{
$update_module = array(
'KM_Number'=>$_POST['KM_Number'],
'KM_Title'=>$_POST['KM_Title'],
'NQF_Level'=>$_POST['NQF_Level'],
'Credits'=>$_POST['Credits']
);
update_knowledge_modules($update_module,$_SESSION['Curr_Code']);
header('Location:edit_km_details.php?success');
exit();
}
else if(empty($errors)== false)
{
echo output($errors);
}
?>
<form action="edit_km_details.php" method="POST">
Well, first of all, you are outputting the "changed successfully" message solely based on $_GET['success'] being truthy. It has nothing to do with whether you had success or failure in your update_knowledge_modules function call at all, which seems odd.
Second of all, I don't see anywhere where you are actually making a database connection.
Third, your query is undoubtedly being formed improperly. Look at this:
$update[] = '.$field. = \''.$data.'\'';
you are going to get a literal $field and backslashes in your query string. Try this:
$update[] = $field . " = '" . $data . "'";
Also where you put your imploded array in the final query, you don't have spaces after SET and before WHERE.
Anytime you are having problems with a query, just var_dump it and run it on the database directly to see why it isn't working and look at your errors, including mysql errors.
Finally, you should not be using the mysql_* family of functions. They are deprecated.
Try: $update[] = $field . " = '" . $data . "'";
Output:
Array
(
[0] => KM_Number = 'blah'
)

Categories