I want to pass my primary key all id value in single url parameter :
PRODUCT TABLE :
id -- int 11 , primary key
name -- varchar
desp -- varecha
table data :
id | name | desp
------------------------
1 | A | f
2 | B | fg
3 | C | ghb
4 | g | bn
below code :
$sql = "SELECT id from product";
$result = mysqli_query($db,$sql);
while ($myrow = mysqli_fetch_array($result)){
$id = $myrow['id'];
// echo $id : 1234
}
hence i am getting id value but i need to pass this "id" value in single URL PARAMETER:
<a href="test.php?test=".$_GET['tes']."&pid=".$id." " >url parameter</a>
note : i cant keep this anchor link in my while loop , as i want this a single link that will be shown in another table
hence my link would be something like :
test.php?test=as&pid=1234
but i am unable to get pid=1234
hence please let me know how i can get the same
Editing answer, as I got your idea wrong.
All you have to do is:
while ($myrow = mysqli_fetch_array($result)){
//.= means that it will connect all values, not override them
$id .= $myrow['id'];
// echo $id : 1234
}
THen echo $id from anywhere.
declare an array outside the while loop : $arr = array();
then write this statement inside your while loop : arr[] = $myrow['id']; this way the array will contain all the IDs and it will increment automatically (you don't have to specify the array index each time). Then you can use that array to get the IDs any time you want. Please if that is not what you want, tell me and explain to me more (because I answered your question based on what I understood so please explain more to me about what you need if it is not the answer). Thanks :)
Related
I have a two columns in database:- copy (which is array) and bookid. My code is;
$query = mysqli_query($db, "select copy from book_outward WHERE bookid like 'B1'");
while ($row = mysqli_fetch_array($query)) {
$copyid = $row['copy'];
}
Database shows like this
+----------------+
| id copy bookid |
+----------------+
| 1 1 B1 |
| 2 2,3 B1 |
| 3 4 B1 |
| 4 2 B2 |
+----------------+
but it stores only last values which was entered in 'B1'. I also tried
$copyid[] = $row['copy'];
but in this case I have to change array keys manually every time.
My aim is to insert copy into column bookid='B1' and before it has to make sure that only UNIQUE values can be stored in database for B1.
HTML :-
<input type="text" name="bookid" />
<input type="text" name="copies[]" />
PHP code for inserting:-
$book_id = $_POST['bookid'];
$copies = implode(',',$_POST['copies']);
$result = mysqli_query($db, "insert into book_outward(bookid,copy) values ('$book_id','$copies')");
As some of the comments mention it it not the best way to to it but it is possible.
You can obtain all the copyid data by:
$query = mysqli_query($db, "select copy from book_outward WHERE bookid like 'B1'");
$copyid = "";
while ($row = mysqli_fetch_array($query)) {
$copyid .= $row['copy'] . ",";
}
$copyidsFromDB = explode(",",rtrim($copyid , ','));
After that you can check if what you got in the request are in there using array_intersect:
$copies = $_POST['copies']
// if not an array use: $copies = explode(",", $_POST['copies'])
if (count(array_intersect($copies, $copyidsFromDB) == 0)
// insert to DB
Solved by myself by adding one line only
`$copies2 = explode(",",rtrim($copies , ','));`
before array_intersect Thanks code helps greatly.
So, sounds to me like the issue is the original data DB schema has some issues.
A sql-like DB is not a great place to put 'array' style value. It already has a mechanism for doing this: a link table.
That'd save you the trouble of having to manually shuffle around your primary keys in this table. It's way easier to check and validate.
If you HAVE to do this via php code, for example you don't have SQL access, like in a controlled build environment, you should take advantage of 'string keys' to on your $copyid, (hint rename to $copyidmap) to group together like pieces of data and preserve key relationships.
so the following would be unique:
map->{bookId}->{copyid}->{id} // Where id is that primary table id. Obviously, validate and do your undefined array assignments.
I have a database table with the following structure. id column is added later. So all id cells are empty.
id | song | album | artist
-----------------------------
| song1 | alb1 | art1
| song2 | alb2 | art2
| song3 | alb3 | art3
| song4 | alb4 | art4
| song5 | alb5 | art5
I have an array which holds the id values for the table. I'll be updating the table (the id column) with the values in the array. For example:
$array = [
"C45Rm3fLGn",
"ocIik81up2",
"IcuSn9T77y",
"tJv7AbF53r",
"a9eZ6xYM5Y",
];
These items are unique random strings.
How should I proceed? I'm thinking about iterating the array and using UPDATE on each item.
$array = [
"C45Rm3fLGn",
"ocIik81up2",
"IcuSn9T77y",
"tJv7AbF53r",
"a9eZ6xYM5Y",
];
$rows = $mysqli->query("SELECT * FROM songs")->fetch_all(MYSQLI_ASSOC);
for ($i = 0; $i < count($array); $i++) {
$row = $rows[$i];
$id = $array[$i];
$mysqli->query("UPDATE songs SET id = '$id' WHERE song = '{$row["song"]}' AND artist = '{$row["artist"]}'");
}
Is there a more preferable way?
UPDATE: I do not use auto increment and the id column didn't exist at the time of table was created. Now, I've added an id column. There are 300+ records. IDs of the records are unique random strings. Before I add another record to the database, every record needs to have a unique random string for its id, so that when I insert a new record, I can create a random string and check if it's unique or not by comparing it to the ids in the table.
At this stage, I just need to update the id column using an array. Array items are irrelevant.
Prepared statements are designed to be prepared once and executed many times, with a minimum of overhead. Using them is also an absolute necessity if the data you're inserting is user-generated.
It's been a long time since I've done anything with MySQLi (I strongly recommend looking at PDO for much simpler code) but this should work:
$array = [
"C45Rm3fLGn",
"ocIik81up2",
"IcuSn9T77y",
"tJv7AbF53r",
"a9eZ6xYM5Y",
];
$rows = $mysqli->query("SELECT * FROM songs")->fetch_all(MYSQLI_ASSOC);
$stmt = $mysqli->prepare("UPDATE songs SET id=? WHERE song=? AND artist=?");
foreach ($array as $i=>$id) {
$row = $rows[$i];
$stmt->bind_param("sss", $id, $row["song"], $row["artist"]);
$stmt->execute();
}
I would also recommend building your array such that it references the columns you're renaming. You're relying on both the database and the array being in the same order, which may not always be the case.
Please try this query:
UPDATE `myTable` SET `id`= CONCAT(item-name, "-id");
Or you can set a counter like this:
UPDATE `myTable`, (SELECT #i := 0) c SET `id`= CONCAT(item-name, "-id-", #i:=#i+1)
I hope this will help you.
Part of a script I am writing requires me to know exactly how a result set gets it's information from a MYSQL query.
I have a standard result from an SQL query, which I then make a row array using fetch_array.
Whilst looping through this content let's say I delete one of the rows I find from the table. If I reset the pointer of the result back to the first, will I find that row again even though it no longer exists, find an empty row, or miss that row entirely?
In other words is the result asking MYSQL for each row as it needs it, or does it get the whole array in one go so it will not pickup on any changes to the table afterwards?
Cheers in advance
EDIT
$result = $conn->query("SELECT ID, value FROM table");
while($row=$result->fetch_array()){
if(x){
$conn->query("DELETE FROM table WHERE ID=$row['ID']");
mysqli_data_seek($result,0);
}
}
The question is will that deleted row be repeated after the reset, get skipped or return something else such as NULL?
No, it will not delete that row inside initial fetched result set.
But of course it will delete the row in your present table.
If you try to reset the pointer, the initial result set with that row still resides. Not unless you overwrite it with another one.
Consider this example. Lets say you have this inside your table:
+----+--------+
| id | value |
+----+--------+
| 1 | test1 |
| 2 | test2 |
| 5 | test5 |
+----+--------+
If you make this kind of operation:
$result = $conn->query('SELECT id, value FROM mytable'); // sample query
while($row = $result->fetch_assoc()) { // fetch all results
if($row['id'] == 5) { // some condition
$conn->query('DELETE FROM mytable WHERE id = 5'); // delete one row in table
}
}
$result->data_seek(0); // reset the pointer
while($row = $result->fetch_assoc()) { // fetch the same result set
echo $row['id'] . '<br/>';
}
It will delete that particular row in your table but not the one in the initial result.
At initial load, it will show:
1
2
5
If you refresh it, now 5 will be gone since its a new request and another result set called.
Firstly, I havent been able to find anything useful on the subject, anywhere really.
I'm trying to make something somewhat simular to a forum,
A small explanation,
(And yes, I know its not seo, but I'm only looking for functionality atm.)
Lets say you go to example.com/?1, Then the database entry with the ID of 1 would be displayed on the index page, If you go to example.com/?3 then the DB entry with the ID of 3 would be displayed, etc..
DB Structure
----------------------------------------
| id | label | description | parent_id |
|---------------------------------------
| 1 | General | NULL | 0 |
| 2 | Public | NULL | 1 |
| 3 | Private | NULL | 1 |
----------------------------------------
PHP Code
if ($stmt = $mysqli->prepare("SELECT id, label, description, parent_id FROM categories")) {
$stmt->execute(); // Execute the query.
$stmt->store_result();
$stmt->bind_result($id, $label, $desc, $parent); // Get variables from result.
while ($stmt->fetch()) {
if(isset($id)) {
echo "Hello, This is the $label category";
}
}
}
What i'm missing is a way to get the users current "isset" (.com/?10, .com/?5, ETC) Before the query is run so i can check for that isset in the DB and get the correct values, right now it's outputting all rows in the DB, I would highly appreciate any help with it :)
If you know of a better way of doing something like this(without using a framework), please let me know!
From a terminology standpoint, it sounds like you are interested in understand what parameters are passed in the request's query string.
In your case, you are doing something a little weird in that be having URI format like /?* where * is integer ID value, you would actually be passing a variably named parameter. Since you don't know what the parameter name is, you would have to do something like
$ids_in_query_string = array_keys($_GET);
To store the key names which infer which ID(s) were requested.
What I would suggest is to form your query string like /?id=*, that way you always know which key in $_GET to check against. For example:
$id = null;
if (!empty($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
}
if (!is_null($id)) {
// perform your query for selected ID
} else {
// do something else
}
I made a simple following-follower system with php(pdo) and mysql. My problem is,
Let's say there is a user name Mike with ID number 99. And Mike has two followers, Greg(id = 77) and Jenny(id = 88)
Greg's following list looks like this (1,2,3,4,99), and Jenny's following list looks like this (5,6,99,7)
What I am trying to do is, when Mike(99) deletes his account, I want to remove id number 99 from Greg(77) and Jenny(88)'s following lists.
Table called 'mytable' has 3 fields. id(INT), following_list(text), follower_list(text).
I've been struggling with this problem for a few days. Can anyone please give me some advice? Thank you so much in advance!!!
Below is my update function
public function update_following_list(){
// $this->myid is Mike's id number(99) who is about to delete his account
// Selecting the list of people following Mike
$query = "SELECT 'follower_list' FROM 'mytable' WHERE 'id' = $this->myid";
$result = $this->dbc->query($query);
foreach($result as $row){
$this->follower_list = $row['follower_list'];
// When I echo $this->follower_list, I get 77,88
// Now querying Greg(77) and Jenny(88)'s following_lists, which have Mike's id number(99) in them.
$query = "SELECT 'following_list' FROM 'mytable' WHERE 'id' IN ($this->follower_list)";
$result = $this->dbc->query($query);
foreach($result as $row){
$this->following_list = $row['following_list'];
// When I echo $this->following_list, I get both Greg(1,2,3,4,99) and Jenny(5,6,99,7)'s following lists
// Here, I am turning following list into array by using explode
$this->following_array = explode(",", $this->following_list);
foreach($this->following_array as $key => $value){
if($value == $this->myid){
// Removing Mike(99)'s id number from Greg and Jenny's following lists
unset($this->following_array[$key]);
// Add back commas, which will then become string
$this->new_following_list = implode(",", $this->_following_array);
// When I echo $this->new_following_list, I get both Greg(1,2,3,4) and Jenny(5,6,7)'s new list without Mike(99)'s id number
// My problem starts here. I was able to remove Mike's id number from Greg and Jenny's lists. But I am having a trouble updating Greg and Jenny's following lists with new following lists.
// The update query below does not work...
$query = "UPDATE 'mytable' SET 'following_list' = $this->new_following_list WHERE 'id' IN ($this->follower_list)";
$result = $this->dbc->query($query);
} // End of if($value == $this->myid)
} // End of foreach($this->following_array as $key => $value)
}
}
} // End of function
This will not scale properly. It's better to normalize your data model like this:
following
user_id | following_user_id
---------------------------
77 | 1
77 | 2
77 | 3
77 | 4
77 | 99
88 | 5
88 | 6
88 | 7
88 | 99
And add two indexes:
UNIQUE(user_id, following_user_id)
INDEX(following_user_id)
To get followers of 99:
SELECT * FROM following WHERE following_user_id=99;
To see who 77 follows:
SELECT * FROM following WHERE user_id=77;
I think your database setup is not optimal. Store comma-separated values in one field, screams for a binding table and some normalization !!
You should have your comma separated value list to be a table/relation, e.g.:
followTable:/ user_id | follows
Deletion of mike's id is then as simple as:
DELETE FROM followTable WHERE follows = 99 OR user_id = 99
The latter makes sure the links between Mike and his followers are being deleted also.