Modify MySQL field based on another with PHP - php

I have a database table that I'm needing to change one field based on another. There are two records for each id "option_id." Each have a sort_order.
So for example:
12345, 1
12345, 2
I need to be able to find any records that have the same ID and have one for sort_order 1, and one for sort_order 2. Then, I need to change the sort_order of 1 to 0, and the sort_order of 2 to 1. I'd like to use php to do this is possible.

Assuming you can handle the connection strings yourself, (I'm assuming PDO here). I had to do number swapping almost exactly like this very recently.
Then do the following:
$sql = "SELECT * FROM table_name WHERE sort_order = 2";
while($row = $results->fetch(PDO::FETCH_ASSOC)){
$sql_1 = "UPDATE table set sort_order = 0 WHERE sort_order = 1 AND option_type_id = " . $row['option_id']; //then execute query
$sql_2 = "UPDATE table set sort_order = 1 WHERE sort_order = 2 AND option_type_id = " . $row['option_id']; //then execute query.
}
The logic is that you find the matching record, change the 1 to 0, then change the 2 to 1. Doing the opposite would really mess up the records.

Related

How to update MySQL two column lookup table where each field is Primary Key

I have a lookup table with two fields and each is a PRIMARY KEY. When I attempt to update the table with PHP, it appears to work but doesn't update. The same query (without the prepared part) in phpMyAdmin works fine.
My PHP is:
$sql = "UPDATE model_laser SET
model_id = :model_id,
laser_id = :laser_id
WHERE model_id = :model_id AND laser_id = :laser_id";
$s = $db->prepare($sql);
$s->bindValue(':model_id', $model_id);
$s->bindValue(':laser_id', $laser_id);
$s->execute();
phpMyAdmin, using the numbers 1 & 27, gives the php code (this works) as follows:
$sql = "UPDATE `model_laser` SET `model_id`= 1,`laser_id`= 27 WHERE model_id = 1 AND laser_id = 17";
Thanks for any assistance as to what I'm missing.
It appears to be your prepared params. You need to differentiate what you are UPDATING TO from what ALREADY EXISTS in your DB
I think it should look something like this:
$sql = "UPDATE model_laser SET
model_id = :new_model_id,
laser_id = :new_laser_id
WHERE model_id = :model_id AND laser_id = :laser_id";
$s = $db->prepare($sql);
$s->bindValue(':new_model_id', $new_model_id);
$s->bindValue(':new_laser_id', $new_laser_id);
$s->bindValue(':model_id', $model_id);
$s->bindValue(':laser_id', $laser_id);
$s->execute();
Your query has two different numbers for :laser_id. One is 27, one is 17. This could be a typo, or a different problem altogether.
$sql = "UPDATE `model_laser` SET `model_id`= 1,`laser_id`= 27 WHERE model_id = 1 AND laser_id = 17";

Sum 3 columns in row for a total column - MySQL & PHP

I have a database which has many columns, but 3 of them I need to sum up. a, b & c .... I need to add a total column for every row (40+ rows) so each time a new score is entered into a,b or c ... the total column is updated for that particular row.
At the moment, I have the following Update that runs to enter a new score.
mysql_query("UPDATE national_reqs SET " . $phase . " = '" .$score . "' WHERE dog_name ='" . $dog_name . "'");
Then when I pull the data back out, I use the following query (and I want to sort by a new "Total" column)
$result = mysql_query("SELECT regfor,cat_num, ipolevel,handler,dog_name,a,b,c,score_time FROM 2015_national_reqs WHERE (id<=190) ORDER BY cat_num ASC") or die(mysql_error());
I think I need a trigger to make this work properly ? I can create a new column for "Total" of type int.
Thoughts ?
update [table] SET a = [value], d = (a+b+c) where id = [id];
Cheers

Update the first row mysql php

I'm trying to update my first row in my database. I use the Limit 1 to only update the first row but nothing is happening. There are definitely matching rows but nothing changes in the database.
Here is the code:
foreach ($player_fromsite as $match_player_in_game) {
//$querytwo = 'INSERT INTO `'.$tablename.'` '.' (`'.$match_player_in_game.'`) '.'VALUES'.'("' . 'yes' . '")';
$querytwo = 'UPDATE '.$tablename.' SET `'.$match_player_in_game.'` = "'.'yes'.'" WHERE `'.$match_player_in_game.'` = "'.'NULL'.'" LIMIT 1';
$querythree = 'UPDATE '.$tablename.' SET `'.$match_player_in_game.'` = "'.'yes'.'" WHERE `'.$match_player_in_game.'` = "'.'NULL'.'" LIMIT 1';
for($a=0;$a<11;$a++){
if($match_player_in_game == $home_players[$a]){
// Insert a row of information into the table "example"
mysql_query($querytwo) or die(mysql_error());
}else{
mysql_query($querythree) or die(mysql_error());
}
}
}
Is the query correct?
In MySQL use IS NULL to compare with NULL.
For example: "UPDATE table SET field = 'yes' WHERE field IS NULL"
NULL isn't a string, so you shouldn't be using = 'NULL', unless you actually set it to that string value. Use IS NULL instead.
You need to define "first row". First row based on an autoincrementing id value? First based on a timestamp date? You need to specify this as MySQL has no concept of "first row".
For example, if you do something like this in MySQL:
SELECT * FROM table LIMIT 1
You are not guaranteed to get the same record back each time.
Most likely you will need to specify an ORDER BY condition on a key column, as without it, you have no guarantee of which row your LIMIT 1 will apply to. I really can't think of a case where one might use LIMIT without an ORDER BY clause, as the two really go hand in hand.
So your query should look like:
UPDATE table
SET field = 'yes'
WHERE field IS NULL
ORDER BY some_key_field ASC
LIMIT 1
Note that even this query would not update the same row every time. It would update the first record (as specified by ORDER BY) that has a NULL value for the specified field. So if you ran this query 10 times, it would change 10 different records (assuming there are that many records with NULL values).

What is the default ORDER BY if I use SELECT statement in mysqli::query

If I have a table like this:
int VARCHAR int
----------------------------------
1 "U" 1
2 "A" 1
3 "B" 1
and I run a query through php's mysqli like this:
$sql = "SELECT * FROM " . parent::GetTableName();
if ($current_user_only == TRUE)
$sql = $sql . " WHERE userID_FK=" . parent::GetUserID();
$result = $this->get_db_con()->query($sql);
if ($result == FALSE)
throw new Exception("SQL exec failed (". __FILE__ . __LINE__ . "): $this->get_db_con()->error");
while ($row = mysqli_fetch_array($result))
{
echo($row[1]);
}
I get an output like this:
2 "A" 1
3 "B" 1
1 "U" 1
That is the result seems to be sorted by the VARCHAR column. If I run the same query in SEQUEL PRO it gives me results in the order I'm expecting which is the order in which they are entered in the table.
Any ideas?
I would never assume any specific order without an order by clause. If you want to have the rows sorted by ID, than use an order by ID.
Short answer: there is none.
Long answer:
For MyISAM tables it's the natural order, i.e. the order in which rows are stored on disk, which is usually the order of insertion. This can be modified by running ALTER TABLE ORDER BY
For InnoDB tables it's the order of primary key.

Update two ID's at once SQL - PHP

I have a table that's PK is an int field.
My problem is I need to swap two of the values round.
This is my current code:
$newId = (int)$id; $newId = $newId - 1;
$result = mysql_query("UPDATE homeScroller SET id = '$newId' WHERE id = '$id'") or die('error '.mysql_error());
$result2 = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'") or die('error '.mysql_error());
The table contains at max 3 rows that contain info for an slideshow on the frontpage of the website. The frontpage orders them by their IDs. So to change the order I need to edit the ID's.
The table contains at max 3 rows that contain info for an slideshow on the frontpage of the website. The frontpage orders them by their IDs. So to change the order I need to edit the ID's.
If that's the case, then your application/database is poorly architect-ed, and you need to re-think your database design before you go any further.
Primary keys should be immutable, i.e.: they should never change. What you're talking about doing is changing primary keys.
Fix your application/database, and you won't have this problem. Are you sure you shouldn't just be adding a new field 'sort_order' and ORDER BY sort_order instead or ordering by the ID field?
Assign one with a temporary id (0, because auto_increment usually starts at 1, so 0 should be unused):
$result = mysql_query("UPDATE homeScroller SET id = 0 WHERE id = '$id'");
$result = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'");
$result = mysql_query("UPDATE homeScroller SET id = '$newId ' WHERE id = 0");
IMPORTANT: However, you shouldn't rely on the primary key for ordering results, if you want to be able to change the order easily. Add a sequence column and sort by that instead.
UPDATE homeScroller
SET id = CASE id WHEN $id THEN $newid ELSE $id END
WHERE id IN ($id, $newid)
Do not use PK for this need.
If you can add timestamp field (shown_at) to this table, do it!
if cant, so update all PKs imultaneously. Just increment them.
For example: suppose we have such strings:
1 photo1
3 myphoto
5 somephoto
than use modulo 3.
1%3 = 1
3%3 = 0
5%3 = 2
increment all records
2 photo1
4 myphoto
5 somephoto
2%3 = 2
4%3 = 1
6%3 = 0
So u can use modulo and increment ids

Categories