Getting last group_id from MySQL in PHP - php

I want to get last added group_id from MySQL to get new $group_id++ for other group.
I tried
$group_id = ("select max(group_id) from posts");
$group_id++;
But when I check it with echo
echo $group_id;
the result is : "select max(group_id) from posts"

You're assigning a query string to a variable..you're not even running the query...?
You need to run the query and assign it to a result ($group_id_)
There's other ways to do this but this is similar to what you're doing.
$result= mysqli_query($conn, "select max(group_id) as max from posts");
$row = $result->fetch_assoc($result);
$group_id = $row['max'];
$group_id++;

This is because you are not executing an SQL query, you are doing an assignment.
The correct syntax is something like this:
$result = mysqli_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Search how you can execute SQL queries, and if you have trouble, post again.
Edit: Have a look on the link below
https://secure.php.net/manual/en/mysqli.query.php

This is the easiest way to implement it the latest one will have the highest ID so you order them by their id starting from the highest id to the lowest and you just take the first one.
Read about the http://php.net/manual/en/book.mysqli.php it explains everything about querying data from your database using php.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($result = $mysqli->query("select group_id from posts ORDER BY group_id DESC LIMIT 1")){
// it has returned a result
$group_id = $result->fetch_object();
$group_id++;
}

Related

How to return integer of COUNT mysql query result in PHP [duplicate]

This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
I'm just putting a simple PHP program together that simply counts the number of total rows in my database and returns the result as a JSON object when it recieves a get request from my frontend.
This should all be super simple but for the life of me I can't figure out how to retrieve the count result in a usable format. All I get from this is "null"
any ideas?
$con = mysqli_connect($servername, $username, $password, $dbname);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$query="SELECT COUNT(*) FROM database";
$result = mysqli_query($con,$query);
$count = mysqli_fetch_assoc($result);
echo json_encode($count);
You can use COUNT as to avoid a very long key.
Here's a code example
$sql = "SELECT COUNT(column) as count FROM mytable";
$stmt = mysqli_stmt_init($db);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_fetch_assoc($result)['count'];
echo $count;
To display data in JSON you can try this:
echo json_encode(['count' => $count])
That by itself will not give you the count.
I would suggest that you start using MySQL object methods instead of functions.
You should also use the "as" satement as way to give a name to the column that has the count value; in my example that column will be known as C .
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT COUNT(*) as C FROM database";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
$row = $result->fetch_assoc();
echo $row["C"];
}
EDIT:
In the specific case of SELECT COUNT you'll only get 1 row, so for this specific example you could do just fetch_assoc().

Trying to output the richest user in my database through php

I know this is a bit of a rookie question but I'm trying to output the richest user's name on my website.
So my table is called Users
I have Column 1 ('Name') containing the names of all the users, and Column 2 ('Bank') containing their account balance.
I would like to find the richest user and output them on my website.
This is what I've got so far.
while ($row2 = mysqli_fetch_array($sqldataGang, MYSQLI_ASSOC)) {
$sqlgetGang = 'select name from gangs where bank = (select max(bank) from gangs) order by bank;';
$sqldataGang = mysqli_query($dbcon, $sqlgetGang) or die('Connection could not be established');
$welthiestGang = $row2['name'];
}
I know that there is a connection to the database as I have other statistics from other tables working... I have no idea why this isn't working... Thanks for the help in advance :)
$sql = 'SELECT name FROM gangs ORDER BY bank DESC LIMIT 1';
That should do it.
You need to fetch a row from your $sqldataGang query object.
Add a line something like this to your program to fetch the result right after your call to mysqli_query()
$row2 = mysqli_fetch_array($sqldataGang, MYSQLI_ASSOC);
But, also, beware. A wise programmer always checks queries for errors. You can see how to do that in the examples here.
Use this query
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT name,bank FROM Users order by bank desc limit 1";
$result = mysqli_query($conn, $sql);
This will give you the richest person in your website

Can't get mysql_query to return any values that exist in the database

I'm using the following snippet:
mysql_connect($host,$user,$password);
$sql = "SELECT FROM ec_opps WHERE id=" . $_GET["UPDATE"];
$item = mysql_query($sql);
mysql_close();
print_r($item);
To try and retrieve data based on the UPDATE value. This value prints to the page accurately, and I know the IDs I'm requesting exist in the database. The print_r($item) function returns no result, not even an empty array, so I'm confused as to where I'm going wrong.
I know it isn't best practise to use MySQL like this, but I'm doing it for a reason.
You're missing columns to be selected in your SELECT query, or you can select all by putting *, which means selecting all column.
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"]."'";
Your query is very prone to SQL injections.
You should refrain from using MySQL. It's deprecated already. You should be at least using MySQLi_* instead.
<?php
/* ESTABLISH CONNECTION */
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT column1, column2 FROM ec_opps WHERE id=?"; /* REPLACE NEEDED COLUMN OR ADD/REMOVE COLUMNS TO BE SELECTED */
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("s", $_GET["UPDATE"]); /* BIND GET VALUE TO THE QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($column1,$column2); /* BIND RESULTS */
while ($stmt->fetch()) { /* FETCH RESULTS */
printf ("%s (%s)\n", $column1, $column2);
}
$stmt->close();
}
$mysqli->close();
?>
Replace with this code
$sql = "SELECT * FROM ec_opps WHERE id=" . $_GET["UPDATE"];
You are missing * in your query.
You need to use:
SELECT * FROM
instead of
SELECT FROM
There is a syntax error in the query. It is missing *. Try with -
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"] . "'";
Please avoid using mysql. Try to use mysqli or PDO. mysql is deprecated now.

sql server ISNULL not working for my query

This is my second question about this problem. I would like get sum of column roll_sum
script:
($sum_number + (SELECT SUM(roll_sum) FROM table_name))
not work because collumn ROLL_SUM is NULL. But if try use replacement:
($sum_number + (SELECT SUM(ISNULL(roll_sum, 0)) FROM table_name))
not work aswell. But second script should replace NULL to 0?
Swap ISNULL() with SUM():
SELECT isnull(SUM(roll_sum), 0) FROM table_name;
I think there is no problem in your sql query but, you are calling sql query in php statement directly.
The below is sample code. please refer to it.
$db = mysql_connect("hostname", "username", "password");
mysql_select_db("dbname", $db) or die("connection failed");
$query = mysql_query("select sum(roll_sum) as sum from table_name", $db);
$query_row = mysql_fetch_array($query);
// to do something you want
$value = $sum_number + $query_row["sum"];
mysql_close($db);

Displaying Database Record MySQLI

I am trying to display a record from my database, however the page appears blank and doesn't display the data I am expecting. The code follows below:
<?php
$mysqli = new mysqli(localhost, root, USERPASS, DBNAME);
$query = "SELECT * FROM usertable WHERE userID= '" . $_SESSION["sess_uid"] . "'";
$result = mysqli_query($mysqli, $query);
$row = mysqli_fetch_row($result);
echo $row['userQuestion'];
?>
Any help would be appreciated.
Thanks
<?php
// there need to be strings arguments here
$mysqli = new mysqli('localhost', 'root', USERPASS, DBNAME);
// sql injection friendly query
$query = "SELECT * FROM `usertable`
WHERE `userID`='{$_SESSION["sess_uid"]}' LIMIT 1;";
// do we have a result
if($result = mysqli_query($mysqli, $query)){
// fetch a single row
if($row = mysqli_fetch_row($result)){
// print the record
var_dump($row);
}
}
?>
You need to wrap 'localhost' and 'root' as strings.
mysqli_fetch_row returns a numerical array.
You can print the content of the record using var_dump or use mysqli_fetch_assoc instead.

Categories