This will need some examples:
For example this is my MySql dump.sql file:
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) unsigned NOT NULL,
`email` varchar(30) NOT NULL,
`username` varchar(30) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
INSERT INTO `user` (`id`, `email`, `username`) VALUES
(1, '[email protected]', 'test1'),
(2, '[email protected]', 'test2'),
(3, '[email protected]', 'test3');
ALTER TABLE `user`
ADD PRIMARY KEY (`id`);
ALTER TABLE `user`
MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
Then i have a db.php file that contains DB connection and a function:
<?php
define('DB_HOST','localhost');
define('DB_USER','test');
define('DB_PASS,'test');
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(DB_USER, $conn);
function get_all($sql)
{
@$db = new mysqli(DATABASE_HOSTNAME, DATABASE_USERNAME, DATABASE_PASSWORD);
global $db;
$q = mysqli_query($db, $sql);
while (($result[] = mysqli_fetch_assoc($q)) || array_pop($result)) {
;
}
return $result;
}
After that i have a sql query that looks like this:
$users = get_all("SELECT * FROM test.user ORDER BY id");
This gives me all the items from the 'user table'.
After that i have an index.php file that uses require_once('db.php') and has the following code to call out all items from the database table like this:
<form>
<table>
<thead>
<tr>
<th>ID</th>
<th>Email</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<?php if (!empty($users)) foreach ($users as $user) { ?>
<tr>
<td><?= $user["id"]; ?></td>
<td><?= $user["email"]; ?></td>
<td><?= $user["username"]; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
All of this works to print out a table with a list of all the users. And now to my question: How can i add the "id", "email" or "username" into some kind of a global variable so i can use the "id" later.
For example i've tried to add the id into $_SESSION:
<td><?= $_SESSION["user_id"] = $user["id"]; ?></td>
And that only shows me the last id if i echo it out:
<?php echo $_SESSION["user_id"]; ?>
...which gives me "3"
What im asking: is there a way to get that "ID", "email" or "username" from each table row and add that into a variable, so i can use it later in other sql queries to either UPDATE or DELETE row using the "ID"?
For example, if i wanted to delete the 2nd user from the "user" table i could use something like:
DELETE FROM test.user WHERE ID = $user_id;
How do i get that $user_id?
mysqlandmyqli. don't do that.mysql_and much of your code is deprecated.