UPDATE query is not working in a while loop - php

I'm new at PHP so please dont bust my chops.
I'm building a Knowledge base system, basic CRUD functionality. I'm getting stuck where i need to NULL all values for each column in a table.
This is basically the "Edit a KB" form. I have a checkbox array which on edit I want to clear the KB number from my category column on my table 'category_kb_members'.
My code works fine apart from this bit.
This is my current code:
//Clear all categories for this KB
while($catrow = mysqli_fetch_array($categorylist)){
$catname = "";
$catname = $catrow['name'];
mysqli_query ($dbc, "UPDATE category_kb_members SET $catname=NULL WHERE $catname ='$kbid';");
}
[Please note no need to comment abut SQL injection here as the source is clean from the database.]
"$Categorylist" is an array of Category names - the table I am updating has a column for each category.
"$kbid" is set from a $_GET from the URL and corresponds with the KB number to be removed and is valid and working.
My loop is to query and update each column to NULL the KB number if it exists in the column. The code later goes on to add these back in the the relevant columns.
I have run this query against MYSQL and it works fine SQL side.
Any ideas as to why the UPDATE is not working?

Thanks for all you're comments. Credits to all who assisted.
I copied my query for $catname
$categorylist = mysqli_query($dbc,"SELECT name FROM categories");
which was further up the code. Although this variable was already set, and working for above code it must have been cleared somewhere above in my code. If I re-run this part above my loop it works fine. I will have to figure out what is overwritting my variable above.
Thanks to all and "Abdulla" for making me think for a 3rd time.

Related

how to echo and compare 2 bit sql value in php

I have saved one data column as bit(2) in my sql table. column name = state2
when i checked the sql table using cpanel I can see the numbers there. I store 0-3 values there so I selected 2 bit as column type.
my sql column updates correctly. but now I am trying to use that value in my if condition. but if condition does not work with that, then I tried to echo the value in each row under column state2.
It prints empty string. why is that ? is there any special method to use with bit(2) data types.
check screenshot for value in sql table
Now this is what I am doing
$state2 = $row['state2'];
echo '<td>'.$state2.'</td>';
I m not attaching full code because it is very long. but I hope this part is enough. I have setup it correctly because it prints other all values correctly in my html page as table row.
look below image and you will see results
what is the reason for this. below image show the data type of state2 column.
please help
I found the reason my self. it was my fault,
I have not added state2 in select statement in sql
I added it and it worked perfectly
https://prnt.sc/u0big4

Clarifications about Multi Queries

I'm trying to execute 2 queries, but whenever I follow the guides online about multi queries, its not doing either of the queries.
What I'm trying to do on the first query is to INSERT or ADD whatever the user inputs on $HISTORY on the record that's currently on colHistory; I.E.:
Current data on colHistory:
A
User inputs 'B' on $HISTORY, the syntax should add 'B' on the 'A' that's currently on record, or 'AB'. Then use the second query to UPDATE all the other records or columns on this particular row.
Here's the code (Please note that the '...' means more code that's unnecessary):
$query = INSERT INTO tbInventory SET colHistory='$HISTORY' WHERE colSerno='$SERIALNUM';";
$query .= "UPDATE tbInventory SET
colImage='$IMAGE',
colSerno='$SERIALNUM',
...
...
colHistory=''
WHERE colSerno='$SERIALNUM'";
mysqli_multi_query($con,$query);
Please note where I declared colHistory as '' before I insert the data from the form. I'm not sure if I'm doing it right on this part. Is there anything that I'm missing?
*Edit:
I have already tried executing the queries one by one as:
mysqli_query($con,"INSERT INTO tbInventory SET colHistory='$HISTORY' ");
mysqli_query($con,"UPDATE tbInventory SET
...
...
colHistory=''
WHERE colSerno='$SERIALNUM'";
Yet it doesn't seem to work either, the whole thing gets ignored.
(** I have a script below the code block above where I could print the results already, and it does run)
Well I can tell you why your first query is broken.
INSERT INTO tbInventory SET colHistory='$HISTORY'
This query is using UPDATE syntax but you are telling the query processor to expect INSERT INTO syntax. So the query is unable to execute.
Decide whether you are needing to UPDATE an existing record or INSERT a new one and alter your query to reflect that. (Change INSERT INTO to UPDATE or change "Set colHistory = '$ History'" to "Values ('$ History', 'col2Val', and so on..")
As for your second query, the syntax looks alright from what you have shown but since you didn't post the entire query its hard to say what is happening there. If you can show more of that query I can update this response.
Here's a good SO question on inserts vs updates.
What are differences between INSERT and UPDATE in MySQL?
I ended up dropping the multi-query method and I did got my intended results by somehow cheating:
I assigned the old data or the data that's currently on the colHistory cell, displayed it, but I disabled the textarea. I then created one more hidden textbox in the script with the old data in it and then hid it to the users view.
I then concatenated both textareas with the new one that I've created that the user could modify, emulating the results wanted.

Change multiple MySQL fields with single query - product code sales

I have a site with products I sell and each product has its own product code. The problem is that recently we changed all product codes to all products.
Because all sales inserted in MySQL before today used the old product code, when I try to get a report to see how many of one product has been sold system find 0 because it looks for the new product code while older sales was inserted with the old one.
Solution:
Even if it is a pain there is no other way than updating all products sold and inserted in MySQL updating the old product code with the new one this way it will work fine.
I need to update like this:
$update = mysqli_query($database, "
update `sales` SET code = 0001 WHERE `code` = '4574645448458'
");
The only problem is that it updates only the first product with this product code but I have houndreds of products sold with the same product code...
How to solve this in some bulk way?
examples of what I will change:
code 4574645448458 for 0001
code 4574645448459 for 0002
and so on
Here is an example of the suggestion from Marc B.
Use a prepared statement and execute it with each pair of "old/new" values.
A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.
For example:
// define an array with all of the code changes as "key/value" pairs
$changes=array(
'4574645448458' => '0001',
'4574645448459' => '0002',
....
);
// define the query string with placeholders
$sql="UPDATE `sales` SET `code`=:new_code WHERE `code`=:old_code;";
// prepare the statement and set up variables to be bound upon execution
$q=$database->prepare($sql);
$q->bind_param(':new_code',$new_code);
$q->bind_param(':old_code',$old_code);
// iterate through "changes", defining the "old" and "new" values for each code change
// execute the prepared statement with each pair of values
foreach ($changes as $old_code => $new_code) {
$q->execute();
}

How do I PHP echo exactly what is stored in a MySQL field?

I feel like there is probably a very simple answer for this, but I've spent about 20 minutes searching and can't find anything.
Basically, I am using PHP to query a table and output the results as a list, using the primary key column (COL_1) of the table to create a link for each record that will bring the user to a detail page for that record. It works fine when the data in COL_1 is a straight-forward string such as "TEST". The edit link will then be detail.php?COL_1=TEST The detail page works by querying the database using the data passed by the link. So in this case it would do a select on the table where COL_1 = 'TEST' and return the correct record.
However, when new line characters are stored in COL_1 things get a bit complicated. For instance, if 'TEST\r\nTEST' is stored in COL_1, when the original query of the entire table is done, $row['COL_1'] for that line will give me 'TESTTEST', which gets passed to the detail page as detail.php?COL_1=TESTTEST, the detail page does a select on the table where COL_1 = 'TESTTEST', and it returns nothing.
However, if I manually link to detail.php?COL_1=TEST\r\nTEST the detail page will query on 'TEST\r\nTEST' and return the correct record.
So basically what I need is a way to do a query and have $row['COL_1'] return 'TEST\r\nTEST' instead of 'TESTTEST'. Does this make sense? How would I go about doing this?
As for why the table is set up like this, don't ask me. I didn't design it. I'd never design keys that can include line breaks like this. But I do have to interact with this table. Bah.
You should encode values that are passed in the URL:
echo urlencode("TEST\r\nTEST");
However, why would TEST\r\nTEST be a primary key? That's crazy. Maybe you need to rethink how you are doing things. Primary keys as integers work nicely.

MySQL update statement not working

I am trying to update a the row in the table 'notes' using the following queries in PHP.
$xyz = mysql_query("Select AVG(x) as AVG_X, AVG(y) as AVG_Y, AVG(z) as AVG_Z FROM `notes_two` where id=".$id);//I am selecting average value of (x,y,x) from another table notes_two
$rowxyz = mysql_fetch_row($xyz);
// Saving the position and z-index of the note:
mysql_query("UPDATE notes SET xyz='".$rowxyz[0]."x".$rowxyz[1]."x".$rowxyz[2]."', actualxyz='".$x."x".$y."x".$z."' WHERE id=".$id);
It is not getting updated.
for starters use sprintf when you are working with loads of variables, or better yet pass them as attributes to mysql. Then just copy your generated sql into phpmyadmin or what other tool your using and sql will provide you with debug info so you can easely see your mistake.
good luck

Categories