Reorder ids to be sequential - php

I have ids separated like 2,3,12,22,23,24, because of adding and deleting items.
So I want to reorder them starting in 1 and set each item sequentially then set auto_increment to the last of them + 1.
I've read similar questions, but no one said why they want this, well I need this because if the ids reach the limit number (255) I won't be able to add more items in the table, and it's ridiculous because there will be like just 30 items in it.
This is probably either easy or I'm missing something, please help me.

As stated in the comments, here's my workaround for your situation (forgive the ugly hacky way to return array key 0.
This is also assuming you're using MySQLi and have already connected to the database
<?php
$query = mysqli_query($con, "SELECT `t1`.`id` + 1 FROM `grpgusers` AS `t1` WHERE NOT EXISTS (SELECT * FROM `grpgusers` AS `t2` WHERE `t2`.`id` = `t1`.`id` + 1) LIMIT 1");
$getID = mysqli_data_seek($query, 0);
$temp = mysql_fetch_array($query);
$id = $temp[0];
Then, on your insert query, add in the new $id.
For example:
mysqli_query($con, "INSERT INTOitems(name,etc.) VALUES ('{escaped postdata}', 'etc.')");
Should then be changed to:
mysqli_query($con, "INSERT INTOitems(id,name,etc.) VALUES (".$id.", '{escaped postdata}', 'etc.')");

Related

How to store a PHP variable from a SQL table INT camp

This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}

How to merge two UPDATE queries into one, different WHERE and SET?

I was wondering if it's possible to combine these two queries as they do not work separately (one of the two only works). They are
$addquery = "UPDATE winners SET mem_name='$addname' WHERE mem_name='$deletename'";
$addresult= mysqli_query($connect, $addquery);
$query = "UPDATE winners INNER JOIN members SET winners.mem_id = members.mem_id
WHERE winners.mem_name = members.mem_name";
$result = mysqli_query($connect, $query);
Can this be done in just one query? Thank you!!!
I am not saying you should do it, but judging from the flow of the code you provided, this is how you could do it.
UPDATE winners w
SET w.mem_name = '$addname'
, w.mem_id = IFNULL(SELECT m.mem_id
FROM members AS m
WHERE m.mem_name = '$addname'
ORDER BY m.mem_id DESC
LIMIT 1
, w.mem_id
)
WHERE w.mem_name = '$deletename'
;
Note, the ORDER BY is technically optional; your question does not state whether mem_name is guaranteed unique in members. If it is unique, the order by should not be needed; if it is not, it at least adds some consistency to the expected value retrieved.
If you have control over the database design, I would suggest removing mem_name from winners altogether. It is/would be redundant data if you were managing the relation primarily by mem_id to begin with.

How to use UPDATE query to update another table

In the Exam1 table, ID, examname, and exam_id values are added fine. But when I try to use the UPDATE query to update the points to another table (Question), it does not work.
for($i = 1; $i<$arraysize; $i++){ //For every question
$questionid = $array[$i]['questionid'];
$points = $array[$i]['points'];
$ID = $ID+1;
$queue ="INSERT INTO Exam1 (ID, examname, exam_id) VALUES
('$questionid','$examname', '$exam_id')";
$result = mysqli_query($connection,$queue);
$queue1 ="INSERT INTO points (ID, points) VALUES
( '$ID' , '$points')";
$result1 = mysqli_query($connection,$queue1);
$sql = "UPDATE Question SET points='$points' where ID ='$questionid'";
$result1 = mysqli_query($connection,$sql);
}
$myquery = "UPDATE Question SET points='$points' WHERE ID ='" . $questionid . "'";
$resultset = mysqli_query($connection, $myquery);
Try this please
First of all be careful with int types and putting values for it in UPDATEs and INSERTs into a quote: There is type cast happening, and it may come to results, which you may not expect.
Second, I still have big trouble to understand your data model of your database: You are joining the Exam1.ID over with the Question.ID. Both appear to be the surrogates for the entity to me. Otherwise I would not understand what the meaning of the column Exam_ID (most likely coming from table Question in your case) should be. It therefore looks to me that the WHERE clause of your UPDATE statement is incomplete (did you also mean to restrict on EXAM_ID? Otherwise you might be setting all points to 20 for all questions irrespectively of the exam...?)
If I got you wrong, please provide a detailed overview about your database schema setup including the primary keys of at least the following tables:
Exam1
points
Question
to allow us further help you (and me adjusting the answer here). Also giving us some insight how you think the foreign key relationship is between the tables might help us to help you.

How to use count in php?

I want to insert data to database. I have a table, named member that has 7 column (ID, User, Password, Address, Phone, Gender, Email). I used count to make auto number like this
$no = "SELECT COUNT(ID)FROM member";
$nors = mysql_query($no);
$nors = $nors + 1;
$query = "INSERT INTO member VALUES (".$nors.",'".$user."','".md5($pass)."','".$name."','".$addr."',".$hp.",'".$gender."','".$email."')";
Why, the result of nors is 6 not 2, although I only have 1 data?
mysql_query returns a result object, not the value. Your query also lacks a needed space between COUNT(ID) and FROM...
$no = "SELECT COUNT(ID) AS count FROM member";
$result = mysql_query($no);
$row = mysql_fetch_object($result);
$nors = $row->count;
You should consider using something more modern like PDO, though, as mysql_* functions have been deprecated and will eventually go away entirely.
edit: #andrewsi noted in the comments that you really should be using MySQL's built-in auto increment functionality for IDs, anyways. Much better than what you're currently doing.
If you're using this to generate the next ID number for a new member, you should look at making ID an auto_increment field instead - as it stands, it's possible that you'll get two members signing up at the same time, and both getting assigned the same ID
Replace this line
$nors = mysql_query($no);
By these lines :
$result_handler = mysql_query($no);
$result = mysql_fetch_array($result_handler);
$nors = $result[0];
If your id field is set to be an auto number you don't need to insert it. MySql will handle that for you. Anytime you add a new row the autonumber is incremented. If you delete a row the autonumber does not decrement.
If you currently only have 1 row but you've added and deleted rows then your insert will produce a row with an ID that is not consecutive.

Incorrect usage of UPDATE and ORDER BY

I have written some code to update certain rows of a table with a decreasing sequence of numbers. To select the correct rows I have to JOIN two tables. The last row in the table needs to have a value of 0, the second last -1 and so on. To achieve this I use ORDER BY DESC. Unfortunately my code brings up the following error:
Incorrect usage of UPDATE and ORDER BY
My reading suggests that I can't use UPDATE, JOIN and ORDER BY together. I've read that maybe subqueries might help? I don't really have any idea how to change my code to do this. Perhaps someone could post a modified version that will work?
while($row = mysql_fetch_array( $result )) {
$products_id = $row['products_id'];
$products_stock_attributes = $row['products_stock_attributes'];
mysql_query("SET #i = 0");
$result2 = mysql_query("UPDATE orders_products op, orders ord
SET op.stock_when_purchased = (#i:=(#i - op.products_quantity))
WHERE op.orders_id = ord.orders_id
AND op.products_id = '$products_id'
AND op.products_stock_attributes = '$products_stock_attributes'
AND op.stock_when_purchased < 0
AND ord.orders_status = 2
ORDER BY orders_products_id DESC")
or die(mysql_error());
}
Just remove your ORDER BY in your UPDATE statement, then put it in your SELECT statement.
sample:
$query = "SELECT ........ ORDER BY ..."
$result = mysql_query($query);
while(....){.... }
UPDATE statement wont accept ORDER BY clause.
You could use a SELECT call to loop through the rows, and include your WHERE and ORDER BY statements there, and then within your while($row = mysql_fetch_assoc($query)){ loop you'd have your UPDATE table SET key = 'value' WHERE id = '{$row['id']}' statement.
Sure, this would require executing mysql_query() a lot, but it'll still run pretty fast, just not at the same speed a single query would.
Why do you need an order by in an update. I think you could just remove it and you update will update everything that respect your where statement.
EDIT: And maybe you could call a stored proc to simplify your code

Categories