MySQLi query to get maximal id in the table? - php

$mysqli = new mysqli("localhost","root","","mydatabase");
if ($result = $mysqli->prepare("SELECT MAX(`id`) AS `id` FROM `mytable` WHERE `row1`=? OR `row2`=?"))
{
$id = 2;
$result->bind_param("ii",$id,$id);
$result->execute();
$result->bind_result($max);
$result->close();
var_dump($max);
}
$mysqli->close();
Unfortunately this code always showing NULL, can u folk explain me how to reach a result?
updated:
in console mode staff like this works great. field id is int and incremental (as PRIMARY INDEX), other fields it's just a rows with a different int values, I cant change anything.
updated:
Well, seems I found the solution:
$mysqli = new mysqli("localhost","root","","mydatabase");
if ($result = $mysqli->prepare("SELECT MAX(`id`) AS `id` FROM `mytable` WHERE `row1`=? OR `row2`=?"))
{
$id = 2;
$result->bind_param("ii",$id,$id);
$result->execute();
$obj = $result->get_result()->fetch_object();
$max = $obj->id;
$result->close();
var_dump($max);
}
$mysqli->close();
this is it.

I figured it out this way:
$result = mysqli_query($con, "SELECT * FROM `TableName` ORDER BY `PID` DESC LIMIT 1");
$row = mysqli_fetch_array($result);
$pidmax=$row['PID'];

You still need to call fetch, as max will only be available after that point. See doc: http://php.net/manual/en/mysqli-stmt.bind-result.php
$result->bind_result($max);
/* fetch values */
while ($result->fetch()) {
printf("Max ID %i\n", $max);
}
$result->close();

Related

Delete Row Result SQL Query

I am new in PHP. I am android developer and does not know PHP enough. I have developed one function which provide me numbers from MySQL database. I want delete that numbers instant as soon as it pass me. I am currently doing it like below
function getAllNumbers() {
require_once("includes/conf.php");
global $conn;
$sql = "SELECT number from number_list WHERE server=1";
$result = $conn->query($sql);
$data = array();
if($result) {
while($row = $result->fetch_row()) {
array_push($data, $row[0]);
$delete = "DELETE number from number_list WHERE server=1";
$result = $conn->query($delete);
}
}
$response["data"] = $data;
return $response;
}
My Table Structure is like below
id int(11) NO PRI NULL auto_increment
name varchar(50) NO NULL
number varchar(50) NO NULL
server int(10) NO 0
status int(1) NO -1
last_act timestamp NO CURRENT_TIMESTAMP
user_id int(11) NO MUL NULL
created_at timestamp NO CURRENT_TIMESTAMP
disable int(11) NO 0
notify int(1) NO 1
fcm varchar(500) NO NULL
But I am feeling that if there any new number arrive in database between number select query and delete query it will delete it without select number in first query. So I am looking to delete only rows which get selected in first query. Let me know if there anything I need to change in my codes.
Thanks a lot :)
So if you select the id in the first query as that is the unique key you can use that to delete just this row
function getAllNumbers() {
require_once("includes/conf.php");
global $conn;
$sql = "SELECT number,id from number_list WHERE server=1";
$result = $conn->query($sql);
$data = array();
if($result) {
while($row = $result->fetch_row()) {
$data[] = $row[0];
$id = $row[1];
$delete = "DELETE number from number_list WHERE id = $id";
$result = $conn->query($delete);
}
}
$response["data"] = $data;
return $response;
}

MySQL AVG function returning 0

I'm using the code below to query the database.
mysql_query ("SELECT * FROM _$symbol ORDER BY date DESC;");
$_10day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 10;");
$_21day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 21;");
$_50day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 50;");
echo "$_10day\n";
echo "$_21day\n";
echo "$_50day\n";
mysql_query ("INSERT INTO _$symbol(_10day) VALUE ('$_10day');");
echo mysql_errno($sql) . ": " . mysql_error($sql). "\n";
I need to get the average of close from the database, and I'm using the AVG()function, then insert the return value into the database. The queries work in mysql however they do not work through the script. It does enter a value into the database, but it always enters 0. What am I doing wrong?
EDIT--solution found
$get10 = mysql_query ("SELECT AVG( close ) AS CloseAverage from ( SELECT close FROM _$symbol ORDER BY date DESC limit 10 ) sub1 ;");
$row = mysql_fetch_assoc($get10);
$_10day = $row['CloseAverage'];
if (!mysql_query ("UPDATE _$symbol SET _10day = $_10day, _21day = $_21day, _50day = $_50day, _100day = $_100day, _120day = $_120day, _150day = $_150day, _200day = $_200day, _240day = $_240day, _20dayVol = $_20dayVol, _50dayVol = $_50dayVol where date = '$date';"))
{
echo "Update query failed";
}
I was querying it incorrectly apparently it needed to be selected as a sub query, solution is above, it is working now.
Here's an example on how to manage multiple result-rows:
function connect()
{
$db = mysql_connect("localhost","username","password") or die("your error msg");
mysql_select_db("database_name");
return $db;
}
$db = connect();
$query = "SELECT value1 FROM my_table";
$result = mysql_query($query, $db);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
// This one will loop through the data in your output//
$outputValue = $row['value1'];
}
For inserting data:
// Continued from the state above //
$query = "INSERT INTO table_name (column1) VALUES (value1)";
$result = mysql_query($query, $db) or die(mysql_error());
$_10day is a mysql result, not a value. You can't just put a result into a query string and expect it to work.
You need to get the result data first, eg;
while($row = mysql_fetch_assoc($_10day)) {
$10day = $row['AVG(close)'];
}
Then you can execute your insert query;
mysql_query ("INSERT INTO _$symbol (_10day) VALUES ('$10day')");
Hope this helps.

How to add results of multiple queries to an array in PDO?

Below is my code
$stmt = $db->prepare("SELECT * FROM inbox ORDER BY `date` DESC ");
$stmt->execute(array());
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$uniques = count(array_unique($row, SORT_REGULAR));
for ($i=0; $i < $uniques; $i++) {
$inbox_id = $row[$i]["inbox_id"];
$stmt = $db->prepare("SELECT * FROM messages WHERE inbox_id=? AND seen=? ORDER BY `date` DESC");
$stmt->execute(array($inbox_id, 0));
$row_msg = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
return $row_msg;
But this is nor returning all data.It is only returning values got from first iteration only.
you can use:
$row_msg[$i] = $stmt->fetchAll(PDO::FETCH_ASSOC);
Your PDO statement is prepared every round inside the loop, that is not necessary and i hope the inbox_id column is a primary key in the inbox table:
$stmt1 = $db->query("SELECT `inbox_id` FROM inbox ORDER BY `date` DESC ");
$stmt2 = $db->prepare("SELECT * FROM messages WHERE inbox_id=? AND seen=0 ORDER BY `date` DESC");
while($id = $stmt1->fetchColumn(0)) {
$stmt2->execute(array($id));
$row_msg[$id] = $stmt2->fetchAll(PDO::FETCH_ASSOC);
}
return $row_msg;
If you do not want a multidimensional array you can just add the row to the result array by using array_merge() (PHP Manual: array_merge) inside the loop (instead of the line with $row_msg[$id]):
$row_msg = array_merge($row_msg, $stmt2->fetchAll(PDO::FETCH_ASSOC));

How to update a value by 1 if the new value inserted into the database clashes with value in the database?

I want to update the database of the sort order column to increase its value by one if the the new value inserted into the database clashes with the value that is already in the database. May I know how should I go about doing it? Please help! Thanks!
Below is my code (I am not sure whether am I on the right track):
$result = mysql_query("SELECT sortorder FROM information ORDER BY id ASC;");
if($result >= 1 ){
$i=1;
while ($initialorder = mysql_fetch_assoc($result))
{
$initialorder = $initialorder["sortorder"];
if ($sortorder == $initialorder ){
$result6 = mysql_query("SELECT * FROM information
WHERE `sortorder` = '$sortorder'");
$row6 = mysql_fetch_array($result6);
$removethis1 = $row6['id'];
$result7 = mysql_query("UPDATE information
SET `sortorder`= ((SELECT `sortorder`
FROM (SELECT MAX(`sortorder`) AS
'$initialorder' FROM information) AS '$initialorder') + 1)
WHERE id='$removethis1'");
}
$query = "INSERT INTO `information`
(`id`,`page`,`description`,`status`,`sortorder`,`keyword`,`date_added`)
VALUES
('$id','$title','$description','$status',
'$sortorder','$keyword','$date_added')";
$result = mysql_query($query, $conn);
header('Location: index.php?status=1&title='.$title);
$i++; }
}
You can do this:
INSERT INTO ON `information`
...
DUPLICATE KEY UPDATE
sortorder = '".$sortorder + 1." '

process sql query results

I got a table named "Serials" with 5 comumns
Serial, Code, Name, Redeemed, Redeem_date
i am selecting some fields from that table with this query:
$query = "SELECT `Name`,`Redeemed`,`Redeem_date` FROM `Serials` WHERE `Serial` = '$serial' AND `Code` = '$code'";
$db->setQuery($query);
$db->query();
But i dont know how to pass these values in the following variables so i can use them in if statements later
$name= //retured value from column Name
$redeemed= //retured value from column Redeemed
$redeem_date= //retured value from column Redeem_date
just like this..
// Your query here..
$query = "SELECT `Name`,`Redeemed`,`Redeem_date` FROM `Serials` WHERE `Serial` = '$serial' AND `Code` = '$code'";
$db->setQuery($query);
$results = $db->query();
//fetch data and stored into variables
while($row = fetch_array($results)){
$name = $row['Name'];
$redeemed = $row['Redeemed'];
$redeem_date = $row['Redeem_date'];
}
try something like this :
<?php
$result = $db->query("SELECT `Name`,`Redeemed`,`Redeem_date` FROM `Serials` WHERE `Serial` = '$serial' AND `Code` = '$code'");
while (list($name, $redeemed, $redeem_date) = $result->fetch(PDO::FETCH_NUM)) {
// DO SOMETHING
}
?>
while ($row = $db->fetch()) {
$name= $row['name'];
$redeemed= $row['redeemed'];
$redeem_date= $row['redeem_date'];
}
this one might fetch your results and assign to vars

Categories