I'm busy with a school project where I need to register users. I created the database and added the tables and can add users. What I just can't get right is to display the next available user id in the table.
I'm using php to retrieve the highest value but when I use echo the variable won't show. There is no error, there is no output at all, just the rest of the page.
Here is the code:
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM users" or
die(mysql_error());
$highest_id = mysqli_query($db, $query);
echo $highest_id;
?>
The code successfully connects to the database, the column is called userid, it contains int values and there are other columns as well.
All other code in the script runs perfectly, it's just this part that I can't get to work.
I have spent the last two days reading and searching for answers and I am at my wits end. Any help would be appreciated.
Thank you.
could be your table is User and not Userid
$query = "SELECT MAX(userid) AS userid FROM users"
Anyway for fetching you should use eg:
$result = mysqli_query($db, $query);
$row=mysqli_fetch_array($result,MYSQLI_NUM);
echo $row[0];
The mysqli_query returns a general object that contains the results array. You have to use the mysqli_fetch_row.
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM userid" or die(mysql_error());
$highest_id_query = mysqli_query($db, $query);
var_dump($highest_id_query); // so you could check the object attributes
//loop results from query
while($row=mysqli_fetch_row($highest_id_query)){
$highest_id = $row['userid'];
echo $highest_id;
}
?>
You could also use the sql statement: SELECT COUNT(*) FROM userid
Be sure to name your tables correctly! SELECT COUNT(*) FROM users
Related
This question already has answers here:
mysqli_stmt::execute() expects exactly 0 parameters, 1 given
(4 answers)
Closed 1 year ago.
So I am new to PHP and I have been on a roll lately developing a website. My question is this. I have all users listed inside of a field in one table.
This is a list of one of these fields: admin, user1, user2, user3.
Now what I need to do is take them users from that ONE field, I am guessing put them into an array and then search each user inside of another table called users and then list the users info such as their rating and bio.
I reposted this with pictures to help you get an idea of what I am looking to accomplish.
I am looking to get the users from this table listed inside of that cell
jobs Table
and find them in this table and then list them
users table
Hey I have edited the code in the following way and I am getting an error.
$jobID = 1;
$jq = $con-> prepare('SELECT applied_names FROM jobs WHERE jobID=1 LIMIT 1');
$jq-> execute();
$jq-> bind_result($usernames);
$jq-> fetch();
$jq-> close();
$stm = $con->prepare("SELECT username FROM users WHERE username IN (?)");
$stm->execute(array($usernames));
$result = $stm->get_result()->fetch_assoc();
$stm->close();
The warning says:
Warning: mysqli_stmt::execute() expects exactly 0 parameters, 1 given on line 14
You can use a subquery and the keyword IN for this:
SELECT * FROM meta_table WHERE userID IN (SELECT id FROM users)
If you post table & column names, I will be able to give you a more precise query.
EDIT:
after seeing your edited post with the images, this way is not possible. you would still be able to use the IN after you have got the field with the usernames in PHP.
$usernames = $row['applied_names'];
$stm = $pdo->prepare("SELECT * FROM users WHERE username IN (?)");
$stm->execute(array($usernames));
And for mysqli:
$usernames = $row['applied_names'];
$stm = $con->prepare("SELECT * FROM users WHERE username IN (?)");
$stm->bind_param('s', $usernames);
$stm->execute();
In my opinion, you should have a users_jobs table with columns id userID & jobID then you can use queries like this:
SELECT username,email,jobName,jobStatus FROM users_jobs
JOIN users ON users.id = users_jobs.userID
JOIN jobs ON jobs.id = users_jobs.jobID
This will produce one row with all the columns you have specified in the SELECT
Just try that :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name, rating, bio FROM Users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "name: " . $row["name"]. " - rating: " . $row["rating"]. "bio " . $row["bio"]. "....<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I am attempting to post a column into my database here as a test and I am unable to do so. I've used the code below and it doesn't seem to be posting. Unless I am missing a trick with PHPmyAdmin I cannot seem to get it working. Any chance anyone could help? Thanks in advance!
<?php
$link = mysqli_connect("XXXX", "XXXX",
"XXXX", "XXXX");
if (mysqli_connect_error ()) {
die("The connection has failed");
}
$query = "INSERT INTO `users` (`email`, `password`)
VALUES('owen#owen.com', 'hfudhf8ahdfufh')";
mysqli_query($link, $query);
$query = "SELECT * FROM users";
if($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo"Your Email is ".$row["email"];
echo" and your Password is ".$row["password"];
}
?>
The problem is that you're only fetching one row of results. Unless the table was empty before you ran the script, there's no reason to expect that row to be the one that you just added.
If the table has an auto-increment ID field, you can fetch that row:
$query = "SELECT * FROM users WHERE id = LAST_INSERT_ID()";
I have following database:
I want to select all columns from 'catalog' table. Used this code, but it doesn't work.
$link = mysqli_connect('localhost', 'root', '', 'technomart') or die('No Connection');
$sql = 'SELECT * FROM catalog';
$res = mysqli_query($link, $sql);
while ($row = mysqli_fetch_assoc($res))
print_r($row);
You state:
I want to select all columns from 'catalog' table.
But your code as displayed says:
$sql = 'SELECT * FROM orders';
Replace the name orders with catalog and you will then be dealing with the data on that table.
syntax:
$sql = SELECT <columns>[, <columns>] FROM <table>
As stated by Biswajit you are also closing your connection before you are returning your data. You should not need to close the connection until the very end of the page.
You are closing connection before fetching data from database. use mysqli_close($link); after your while loop.
I'm developing an app for android that uses a DB on a server.
I wrote some script php to create new rows in some tables and get all elements from a table (using JSON to exchange data between android and mysql).
Now I have a problem:
i need to select an id from a table and then use this to insert a row in anothere table that has this foreign key.
Well, when I try to select my id, i don't know why, but look like it doesn't work.
Here a simple example how I select this id:
//connect to DB...
$result = mysql_query (*SELECT id FROM 'table' WHERE name = $name );
$row = mysql_fetch_assoc($result);
$id = $row['id'];
When i use this to select an id, and put it in another query (always on the same connectio) nothing is stored.
if I force the value manually, and so in the same second query I put a number of a preesisting id, the insert works, so the problem is in this piece of code.
Hope someone could help me.
Thank you!
The code that you have put on the question, contains syntax errors.
- Remove * from the start of query
- put the query inside " "
- remove single quote ('table') from table name
Here is the modified code:
//connect to DB...
$result = mysql_query ("SELECT id FROM table WHERE name = $name" );
$row = mysql_fetch_assoc($result);
$id = $row['id'];
Also you should escape the parameter $name in query. And you should use mysqli or PDO instead of mysql extension.
try this:
$result = mysql_query (*SELECT id FROM 'table' WHERE name = $name );
$row = mysql_fetch_assoc($result);
while($row > 0){
$id = $row['id'];
}
Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);