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
Related
why it's not working..
i want to update my table in database this is my code.
for ($i=0; $i <83 ; $i++) {
$link="this is test".$i;
$sql = "UPDATE tbl_gallery_images SET thumbnail_url='$link' WHERE gallery_id=1";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
echo $link."<br>";
}
when i echo that link it's show 100% right but in db just update 82 number in all rows even it is in loop.
thanks in advance.
UPDATE tbl_gallery_images SET thumbnail_url = '$link' WHERE gallery_id = 1
As it is, this query updates column thumbnail_url in all records that have gallery_id = 1. Running the same query 84 times in a loop results in the same set of records being updated again and again in each iteration, with an increasing thumbnail_url. After the last iteration, all records where gallery_id = 1 end up with thumbnail_url = 'this is test83.
A sensible solution would be to add another criteria in the WHERE clause, in order to update just one record per iteration. Assuming that you have some integer column called id to disambiguate the records where gallery_id = 1, you would typically go:
`UPDATE tbl_gallery_images SET thumbnail_url = '$link' WHERE gallery_id = 1 AND id = $i`
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.
I have around 1000 records in my MySQL database. I recently added a new column called UniqueKey and I want to update all rows in my table with a random, unique key.
This is what I got:
$updatequery = "SELECT * FROM pictures";
$resultt = $conn->query($updatequery);
while ($roww = $resultt->fetch_array()) {
$rowws[] = $roww;
}
foreach($rowws as &$roww) {
$UniqueKey = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey'";
mysqli_query($conn, $sqlupdate);
}
The problem here is as follows. It DOES create a UniqueKey, but it uploads this new random value to ALL my rows. How can I do this?:
generate random key by $UniqyeKey
Insert this key in the first row
regenerate a new key and insert this in the next row
etc etc
Thanks in advance! Have been trying to fix this for hours..
There is no need to use the extra foreach loop. You can do the all the job within the while loop itself, as follows:
while ($roww = $resultt->fetch_array()) {
$UniqueKey = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey' WHERE id = '".$roww['id']."'";
mysqli_query($conn, $sqlupdate);
}
Note: The given example assumes that id is the Primary Key in your table. You can change that accordingly
Related: Setting value for one column of all records in table
Without a where clause an update updates all the records. So update your query from:
UPDATE pictures SET UniqueKey = '$UniqueKey'
to:
UPDATE pictures
SET UniqueKey = '$UniqueKey'
where id = ?
or something like that where it identifies the one record you want to update each time.
Also you don't need the foreach, do it all in the while loop.
The others have already solved the issue with updating all rows at once.
But if you truly want to have unique values, I would suggest to add a UNIQUE constraint to your UniqueKey column.
In addition, you could put your generation of the unique key and the update query in a do-while loop like this:
while ($roww = $resultt->fetch_array()) {
do {
$UniqueKey = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey' WHERE id = '".$roww['id']."'";
} while (!mysqli_query($conn, $sqlupdate))
}
The combination of these two steps would ensure that the key is Unique and is properly inserted in the database.
You need to set a Where clause to update the rows you want. Foreach only loops you through the result set you get from the select, you are not actually inside the database. When you do
$updatequery = "SELECT * FROM pictures";
$resultt = $conn->query($updatequery);
You are assigning to $resultt the result of that query, you are not actually 'inside' the database. When you then query:
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey'";
mysqli_query($conn, $sqlupdate);
You are updating ALL UniqueKeys to the same one. Your foreach loop does nothing, it only loops through your result set and updates the key $rowss times. Basically, you are updating all keys #rowss times. I assume you have an autoincrementing ID in your table?
If so, you can delete your foreach loop and replace it with:
$idresult = $conn->query("SELECT id FROM pictures");
while ($row = $idresult->fetch_assoc()){
mysqli_query($conn, "UPDATE pictures SET UniqueKey = '$UniqueKey' WHERE id = " . $row['id'];
}
You're updating every single row because you're not using a WHERE clause.
Do something like this:
foreach($rowws as &$roww) {
$UniqueKey = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey' WHERE primary_key=".$rowws['primary_key'];
mysqli_query($conn, $sqlupdate);
}
Where primary_key is the PK column of your table.
What I'm trying to do is count the votes when someone votes on a "page". I think I lost myself trying to figure out how to track when a member votes or not. I can't seem to get the code to tell when a member has voted.
//Generate code ID
$useXID = intval($_GET['id']);
$useXrank = $_GET['rank'];
//if($useXrank!=null && $useXID!=null) {
$rankcheck = mysql_query('SELECT member_id,code_id FROM code_votes WHERE member_id="'.$_MEMBERINFO_ID.'" AND WHERE code_id="'.$useXID.'"');
if(!mysql_fetch_array($rankcheck) && $useXrank=="up"){
$rankset = mysql_query('SELECT * FROM code_votes WHERE member_id="'.$_MEMBERINFO_ID.'"');
$ranksetfetch = mysql_fetch_array($rankset);
$rankit = htmlentities($ranksetfetch['ranking']);
$rankit+="1";
mysql_query("INSERT INTO code_votes (member_id,code_id) VALUES ('$_MEMBERINFO_ID','$useXID')") or die(mysql_error());
mysql_query("UPDATE code SET ranking = '".$rankit."' WHERE ID = '".$useXID."'");
}
elseif(!mysql_fetch_array($rankcheck) && $useXrank=="down"){
$rankset = mysql_query('SELECT * FROM code_votes WHERE member_id="'.$_MEMBERINFO_ID.'"');
$ranksetfetch = mysql_fetch_array($rankset);
$rankit = htmlentities($ranksetfetch['ranking']);
$rankit-="1";
mysql_query("INSERT INTO code_votes (member_id,code_id) VALUES ('$_MEMBERINFO_ID','$useXID')") or die(mysql_error());
mysql_query("UPDATE code SET ranking = '".$rankit."' WHERE ID = '".$useXID."'");
}
// hide vote links since already voted
elseif(mysql_fetch_array($rankcheck)){$voted="true";}
//}
You are making it too hard. Use a numeric value for the vote, +1,-1, and enforce a unique constraint on the table:
Expanded a bit:
create table votes (
pageId int references pages (pageId)
,memberId int references members (memberId)
,value int check (value in (-1,1))
,constraint votes_unique unique (pages,members)
)
Now you can "Select sum(value)..." to get what a user is up to, what's going on with a page, etc.
something like this should work for you - just replace all things image with all things code.
PHP: Star rating system concept?
Your first query is invalid as it has two WHERE clauses.
I am using PHP/MYSQL. I want in my frontend, for the users to sort and rearrange database records entered by the user himself in an earlier stage. The records uploaded by the user may sometimes inserted into the database randomly, so in the user profile he/she might have a facility to rearrange the the rows in the database according to there wise.
Can any one provide me a script that would help me to do so.
id title date desc
1 s1 s1_date s1_desc
2 s2 s2_date s2_desc
3 s3 s3_date s3_desc
4 s4 s4_date s4_desc
5 s5 s5_date s5_desc
In the user profile he want to rearrange the rows so that s2 will go one up and will save as s2->s1 and s1->s2 for every field.. may be swapping of records in between
I am looking it in another way.. user page will show the field in rows wise and in the side there will be an input box of each the current row id say (id) is set as value of that input box so that the user can change in between and submit the whole reordered list to the back-end. In that case what can we do... there will be many swapings to to concurrently..
Best solution is to add another field "ordering" where you can store by default int ID, and while rearranging rows, you could swap values of ordering between these rows. In query you would do ORDER BY ordering ASC/DESC
Get both rows and update back the values:
Assuming the tablename is: t
$result = mysql_query("SELECT title, `date`, `desc` FROM t WHERE id = 1");
$row1 = mysql_fetch_assoc($result);
$result = mysql_query("SELECT title, `date`, `desc` FROM t WHERE id = 2");
$row2 = mysql_fetch_assoc($result);
mysql_query("UPDATE t SET title = '{$row2['title']}', `date` = '{$row2['date']}', `desc` = '{$row2['desc']}' WHERE id = 1");
mysql_query("UPDATE t SET title = '{$row1['title']}', `date` = '{$row1['date']}', `desc` = '{$row1['desc']}' WHERE id = 2");