Updated Individual Rows in PHP/MYSQL - php

I am retriving data from a SQL DB which I am stroring in a form. I have a update page however, I dont know how I can update table according to what the user wishes to change and hence update the database.
This is what I mean. Say after running the query I have the output :
Product | Descption | Quantity | Price | StartDate | End Date
chcolates xyz 2.0 4.99 2013-03-11 2013-03-20
sweets yum! 1.0 1.99 2013-03-15 2013-03-27
so this is being outputted as a table in php by queuing the db.(i.e. this seller is selling 2 products mentioned).
Now say the user wanted to update the first row and change the quantity for example. Then how can I do this? I know I can use the SQL QUERY UPDATE TABLE sellers WHERE ??
Should I output a table or a form? The user is able to update any row they wish and any field also. (i.e. can update the product they wish to sell, descp, quantity etc.)
How can I go about doing something like this? Any ideas please?
====EDIT======
Thanks for everyones suggestions. I have a formatting error. I am inside my php tags and after running the query as such:
while($rows = mysql_fetch_assoc($querySellers)){
echo 'Product:'.'<br />'.'<input type="text" value = $rows[\'ProductName\']>';
This does not seem to be printing the VALUE of the query from the DB and instead prints
$rows['ProductName']
inside the text box this is a formatting error right? What can I do to solve this? And also initially the productName is a drop down combo box... Is there a way I can do it so that when I run the query the output is shown as the SELECTED combo box option?
Thanks once again.

The best thing you should do is implement an ID column (auto increment maybe?) or some unique identifier (Primary Key) to the items in the table. This way, you can easily edit one item by doing
UPDATE table SET value = 'value' WHERE id = $id
In your case, you do not have any unique identifier so you would have to build a large WHERE statement to include everything ie.
WHERE Product = 'chocolates' AND Description = 'xyz' AND .. AND..
and this may not be entirely unique.
EDIT: (in reference to edit)
The problem is how PHP handles single quotes vs. double quotes. PHP will NOT evaluate variables in single quotes but will in double quotes.
$myvar = "value";
echo '$myvar'; // output: $myvar
echo "$myvar"; // output: value
So you need to change your construction
echo "Product: <br /> <input type=\"text\" value = \"{$rows['ProductName']}\">";
Notice the change of single quotes to double and the escaping of the double quotes.
As for your question on the selected option. You need a way to determine which is selected and add an IF statement with the code to add Selected attribute to the option.

You need to have an id with primary key that auto increaments, not null.
THen
UPDATE `your_db_table`.`column_table` SET `Product`
= 'Sweet Stuff' WHERE 'Product`.`prod_id` = 1 LIMIT 1;
Then the rest of the stuff is is clearly explained by #UnholyRanger

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

Search value in table, if the value is not found, auto insert

Is it possible to search for a value in MySQL and if the value is not found, automatically insert that value?
For example:
This is my table. The id is auto increment, the case id is inserted by me
when I search for a number on my search box. If that number is not inside the table, it will auto insert it into the table.
id| case id
1 | 324
2 | 789
3 | 314
when me search 123 on my search box.that number of 123 is not in my table so that number of 123 will auto insert into my table.
id | case id
1 | 324
2 | 789
3 | 314
4 | 123
Is this possible?
here is my code
mysql_select_db($database_connection_db, $connection_db);
$query_viewAduan = mysql_query("SELECT No_KP, COUNT(*) FROM aduan_tidak_hadir WHERE No_KP LIKE '%".$no_kp."%' GROUP BY No_KP;");
while ($row = mysql_fetch_array($query_viewAduan))
{
if (!$row['COUNT(*)'])
{
echo 'satu';
}
else if ($row['COUNT(*)'] == '1')
{
echo 'dua';
}
else if ($row['COUNT(*)'] == '2')
{
echo 'tiga';
}
}
Yes this is possible but not with simple sql statements. This has to be done with an extension of sql called PLSQL. If you know PLSQL then continue reading or otherwise stop right here and learn it befor you read this full answer.
Here's the code for you question:
declare numb my_table.case_id%type
begin
select case_id into numb from my_table where numb=case_id;
exception
when no_data_found then
insert into my_table values(/*you said the id auto_increments so I'm leaving this one out*/,numb);
end;
Since I didn't know the name of your table I just called it my_table. Try this and it should work.
A quick note before I move to an answer. Any time you ask a question, whether it be on the web or to another person, you should have tried something already. This is true for any subject. If you want to drive your car, you must first try to start it. It might be obvious that you tried that, but in a more technical subject, we need to know that you in fact did try something, and that what you tried did not work. A lot of times these questions get asked because the users have in fact tried nothing at all. It is important that you try something, because that is your real learning experience. Just following a set of instructions given to you here will not help you in the future.
Now on to helping you figure out your problem. You have flagged your question as a PHP and MySQL question, which suggests that you don't need to do it in a single MySQL query. I won't give you the code to do it, but I will point you in a direction for some sample code.
Let's break down your question into the actual steps:
Search value in table
This is the first part of your question. This is a basic select statement. I'm sure you can figure it out. If not, google for MySQL select.
if the value is not found
This is the second part of your question that essentially defines what you must do in PHP. You need to check if the value was not found. You need to look at the results of select statement from your search value in table step and determine whether or not it was empty or contained results.
auto insert
At this step, based on your last step if the value is not found, we can determine whether or not we should insert the value. For instructions on how to do an insert, Google mysql insert.

Dynamic textbox creation with db using ajax/javascript/php

I have two tables. company_details and company_specials. Each company_details can have multiple specials. I display the company details at http://eurothermwindows.com/ed/admin.php
The first row and fourth row that has the 0 in the active column is from company_details and the rows below are from company_specials.
Currently the code allows for dynamic modification of the company_details rows as denoted by the compid in that table. However i would like to have the rows below it to be dynamically modified as well but it's using the same compid and i'm not sure how to separate them in the code.
Code below is the code being generated for the company_specials. I need a way to uniquely identify each row and be able to modify it.
http://pastebin.com/RAe9iwAP
Could somebody provide some guidance please? I'm thinking that i would probably need to uniquely identify each of the specials within the company_specials or set some sort of pointers?
Add unique ids to your db tables and output hidden text fields with each record to indicate it table origin and its id. this will allow the code to know which table had which row updated or deleted. inserting new records can be accomplished by offering a blank record of each type at the end of each group, so there would be one blank specials record at the end of each group and one blank company record at the end of the table.
Put a unique name on each input field of the form name='comp[<?php echo $comp_id?>][<?php echo $comp_field_name?>]' and name='spec[<?php echo $spec_id?>][<?php echo $spec_field_name?>]' so that when the table is posted, PHP will see two arrays, $comp and $spec. You can loop over these with
foreach ($comp as $id=>$row)
{
}
and loop over each $row to build an SQL update or insert statement with
foreach ($row as $fld=>$val)
{
}
Seems you're on the right track. You will indeed need to identify the rows uniquely. You could add a unique id to your company_specials table and use that. Or use some other combination of attributes that's unique to each row in your company_specials table (e.g. concatination of compid & specdate). Whatever fits your information-structure. I would advise to just add a unique id to your specials table.
Be sure to also add that unique-constraint to your database-system to prevent invalid data from being entered.

MySQL id numbering in table

Let's say that I have a table linked to a database like this: http://www.falkencreative.com/forum/records/view.php
How do I make it so that when I delete a record and then add a new one, the new replaces the previously deleted record and has the previously deleted id number instead of the next id?
For example
Red
Blue
Green
click button to delete green.
Red
Blue
click button to add new color.
input orange
Red
Blue
Orange
As it stands, what I'm working with is putting out:
1. Red
2. Blue
4. Orange (What should set this to 3?)
It's probably something simple in terms of the table set up, but I have no idea what to do and I'm pressed for time. Can anyone guide me on what I should do?
You may have 2 options. Either update the same row where the "Green" value was previously. i.e.:
mysql_query("UPDATE table_name SET color = 'orange' WHERE ID = '3'");
or
mysql_query("UPDATE table_name SET color = 'orange' WHERE color = 'green'");
or
whatever your specifiers could be.
this should be from the MySql standpoint the easiest way. Or you can delete it as you initially outlined and re insert new row with mysql_query("INSERT INTO .... but then MySql PK UID will need to be reset i.e.:
mysql_query("ALTER TABLE table_name AUTO_INCREMENT = 1");
which will remove your used PK IDs and renumbers all rows. Or is there an easier solution ?
No, when you delete a database row, if the column have the AUTO_INCREMENT active, it will take the value from a sequence.
If you delete 3, the sequence always start from 3+1.
You can see\set the auto-increment value for example from php myadmin.
I don't know what DBMS are you using, but with oracle you can manipulate the sequence.
So you have various way.
Complicated: When you insert\delete you update the sequence with the triggers
You use 3 coloumn: id, IdToShow, Value.
id is the same of now, you use it with autoinc.
idToShow also is what you show. When you insert you can insert it counting the rows present in the table (you have various ways).
Hope it help.
Your problem is not about database IDs, it's about not understanding the difference between an ID and a line number. They have nothing to do with each other. Just simply output the loop counter ("$i") instead of the ID.
<?php
for ($i = 1; $i <= foo(); $i++) {
print "<tr><td>{$i}</td><td>...</td></tr>\n";
}
?>
I think you want to UPDATE the record, rather than DELETE the old and INSERT a new one.
Edit:
If you want to insert a new record and assign it the next sequential id, use a non-auto_increment column and do this when adding a new record:
INSERT INTO myTable (id, ...) VALUES ( (SELECT MAX(id) + 1 FROM myTable), ...)
I don't have a database handy to test this, but I think it will work. But I'm not sure what will happen when the table is empty. Also this may create a race condition.

PHP, MySQL: mysql substitute for php in_array function

Say if I have an array and I want to check if an element is a part of that array, I can go ahead and use in_array( needle, haystack ) to determine the results. I am trying to see the PHP equivalent of this for my purpose. Now you might have an instant answer for me and you might be tempted to say "Use IN". Yes, I can use IN, but that's not fetching the desired results. Let me explain with an example:
I have a column called "pets" in DB table. For a record, it has a value: Cat, dog, Camel
(Yes, the column data is a comma separated value). Consider that this row has an id of 1.
Now I have a form where I can enter the value in the form input and use that value check against the value in the DB. So say I enter the following comma separated value in the form input: CAT, camel
(yes, CAT is uppercase & intentional as some users tend to enter it that way).
Now when I enter the above info in the form input and submit, I can collect the POST'ed info and use the following query:
$search = $_POST['pets'];
$sql = "SELECT id FROM table WHERE pets IN ('$search') ";
The above query is not fetching me the row that already exists in the DB (remember the record which has Cat, dog, Camel as the value for the pets column?). I am trying to get the records to act as a superset and the values from the form input as subsets. So in this case I am expecting the id value to show up as the values exist in the column, but this is not happending.
Now say if I enter just CAT as the form input and perform the search, it should show me the ID 1 row.
Now say if I enter just camel, cAT as the form input and perform the search, it should show me the ID 1 row.
How can I achieve the above?
Thank you.
The function you're looking for is find_in_set:
select * from ... where find_in_set($word, pets)
for multi-word queries you'll need to test each word and AND (or OR) the tests:
where find_in_set($word1, pets) AND find_in_set($word2, pets) etc
IN() Check whether a value is within a set of values
mysql> SELECT 2 IN (0,3,5,7);
-> 0
mysql> SELECT 'wefwf' IN ('wee','wefwf','weg');
-> 1
SELECT val1 FROM tbl1 WHERE val1 IN (1,2,'a');
View: IN MySql
I've got several things for you in terms of feedback & in direct response to your questions:
First, I suggest you sanitize the input. Everybody is going to tell you that. For that, see What’s the best method for sanitizing user input with PHP?.
Second, normalize the input with UPPER() or LOWER() if you want to use MySQL and need to store user-formatted input, or use strtoupper() and strtolower() if you wanted to process the input before storing it.
You're still left with the order in the user query. E.g. "cat, dog" ought to yield the same result as "dog, cat". If you were to code that with a LIKE statement, performance issues are going to eat you alive. Not only would you have to create the query dynamically, you'd also end up with huge and unnecessarily complex queries. In short, forget it. You have to change the way you store your data.
One way to accomplish this is by creating a relationship table that references a table of unique user input and your record. This table would look similar to
user_id | pet_id
Every user could have more than one pet_id associated with them. I've set up a database a long time ago the same way you did and ran into the same issues. Performance-wise it never paid off and it's anything but good style. I ended up changing my structure because of that to the above-mentioned method.
This mysql function search an INT value into a json array of INT:
-- EXAMPLES :
-- select is_into_json_array(18, '[25, 10, 15]'); -> -100
-- select is_into_json_array(25, '[25, 10, 15]'); -> 0
-- select is_into_json_array(15, '[25, 10, 15]'); -> 2
https://github.com/PietroLaGrotta/Json-in-mysql-text-type/blob/master/is_into_json_in_array.sql
Yes, the column data is a comma
separated value
Here is your fault.
No, it shouldn't be comma separated value
And your database structure should be normalized.

Categories