PHP get the max value from database - php

Hey I am trying to get the max id from in my database using a one line of code.
Have this code that is working, however I know that there is a better way to do without using three line of code. One more thing I am using xammp for my database.
$result = #mysqli_query($connection, "SELECT MAX(Cust_ID) FROM customer");
$row = mysqli_fetch_row($result);
$getlastID = $row[0];
I was hoping that someone can help me, please.

The fact is, with mysqli there are three steps to what you are doing. If you were using PDO, you could use fetchColumn to combine the last two steps into one.
Just for the sake of argument, you can actually combine those three lines of code into one, by wrapping the query in the fetch row and dereferencing the result directly:
$id = mysqli_fetch_row(mysqli_query($connection, 'SELECT MAX(Cust_ID) FROM customer'))[0];
I would not recommend doing it this way, though. It will be easier to debug your script if each of these instructions is executed in a separate statement. Less code is generally better, but not at the expense of maintainability.
Incidentally, you should avoid using the error control operator (#). If there are errors, you want to know about them so you can handle them rather than ignoring them. There may be some valid uses for it, but this is probably not one of them.

Related

Some Tips to properly number SQL queries

As an Amateur PHP Developer I often have this problem of mixing sequences and variables.
SHORT :
So what would be the tips to keep in mind when writing a webpage that has many SQL queries.
I have thought of an idea of making a function but I am not sure if that would be of any good.
LONG:
The problem is I have a PHP page that has many sql queries which are followed by result, row , row_number, and die() if result unsuccessful after running the query.
I number them as sql1, result1, row1, error1, mysqlouput1 and sql2.... and so on..
When I add one more query after five or six days I have to go through the whole code to find out which was the last sequence used and take the next one, many times i just use the same and it creates strange problems.
The same problem with variables, as the same page is loading again and again with different POST and GET ids keeping track of variables is just too messy.
So what would be the tips to keep the code well sequenced, readable and variable names unique and understandable.
I have though of writing a function that takes the SQL as the input and gives the result, row, row count, and error as output.
What would you experienced people suggest ?
Thanks.
at first you should really try to just use relevant names for your variables.
Like if you are lookin for all the users use variables like $sqlUsers, $queryUsers, $resultUsers/$usersArray
The idea with the function would be one way to tackle the problem, as it no longer possible to code errors in the process itself, so if you do not want to switch to objectoriented programming I would probably choose that way.
Another way would be a mix, you could create only some classes in which you handle the database-interactions for specific domains. I.e. class userDataHandler would have the methods getUserById(), getAllUsers() et cetera. This way you would still have to write the querying process, but you know exactly where your queries are, have them in a structured way, there are no problems with naming your variables inside the methods, and your code doesn't get messy as you have different files for different domains -> separation of domainspecific code.
Can you explain your problem with the request-variables($_POST and $_GET) a little more? Why does your site get called with so many different variables, maybe you could structure your application a little better.

Is it possible to select all id's without a while-loop

I'm not sure if there is an answer for this, but I was thinking about the fact that PHP isn't very fast with while loops. That got me thinking about a basic function, which does something like this:
$array = array();
$sItem = DB::cms_query("SELECT id FROM someTable");
while($fItem = $sItem->fetch_assoc() ){
$array[] = $fItem['id']; // store the id in an array
}
That will give me an array with all found id's. What I was wondering is this:
Is it possible to select all those id's in 1 query and only use one fetch (so no loops to fetch), without creating difficult code. The goal is a simple piece of code to select all id's.
Small edit: I could replace fetch_assoc() with fetch_row() to improve a tiny bit, but I'm looking to replace the loop
To answer some questions:
I'm using mysqli, in my own custom database class (I'm new to OO, so in time I might improve that, but thats another story)
No, the mysqli extension doesn't provide any way to fetch all rows with a single operation, you can only fetch them one at a time. The only PHP API that currently offers this feature is PDO.
but I was thinking about the fact that php isnt very fast with while loops
How much ids are you fetching and what is called "not fast" for you?
I think the reason for a bad performance would most likely not be a while loop, but some other glitch with your code...

PHP MySQLi possible issue with escaped parameter in escaped statement?

This is something I have been trying to figure out for a bit, it is the most simplest of queries that does not seem to want to work for me (only in php mysqli, works in console sql)
First I am using a prepared statement, merely looking for a match on a specialized id (from another service) to update the relation to use my primary key for easier searching on my end.
The query is as follows:
$query = "SELECT id
FROM {$this->config->dbprefix}{$table}
WHERE sf_id = ?
LIMIT 1";
I use this as one line, I split it up for better readability here
I then check that the prepare statement is valid (I do this in multiple places and it works everywhere else.
if(!($ret = $this->dbo->prepare($query))){
//handle error, this part is never called
}else{
//everything is fine, code in here is below
}
Up to here everything seems fine. Checking table and prefix manually shows they are working and referencing the proper table.
$ret->bind_param('s',$id);
$ret->execute();
$ret->bind_result($retId);
$ret->fetch();
$count = $ret->num_rows;
The problem is here, the query always returns 0 for the num_rows. Checking the query manually and trying it in console returns 1 result as it should. So far with it being such a simple query I just cannot wrap my head around why it would work elsewhere, but not here. I am sure this is the proper way to build it (I have many other queries structured similar).
Is there any kind of confusion I may be experiencing? Something easy to miss that could cause a query like this to not return results?
EDIT:
I have attempted further error handling, and trying an if test on execute does not trigger an error, though I will try more.
To expand I have a raw output of the $query variable and the id variable. By combining them and manually attempting the query in console I get the proper result. My thoughts are on somehow the prepare statement is escaping, causing the string variable $id to not properly match. Though that is just speculation.
You need to call store_result() before trying to access num_rows. Without it, the statement handle does not know how many rows are in the result set.
$ret->bind_param('s',$id);
$ret->execute();
$ret->bind_result($retId);
$ret->store_result();
$count = $ret->num_rows;
// perhaps add error handling based on number of rows here
$ret->fetch();

PHP Update class (OO)

I have written a PHP OO class which will update 4 fields of a certain row in a table. For now the row is decided by a constant (user with name 'jip')
I have corrected the query in a previous post here, so i'm pretty sure the query itself is fine. So, there must be some sort of error within the class itself. Probaply the vars don't reach the query somehow. I have been looking for hours, but can't find the problem. I have linked both files of the class, since i downt know where the error is, the values just don't show up in the database. If anyone would like to check them, (s)he'd make my entire week! SO here is the link and i hope someone is willing to help :)
UpdateForm.php: http://pastebin.com/dUaZPrn6
Update.class.php: http://pastebin.com/6mnL4DzE
Try replacing mysqli_real_escape_string($conn, $variable) with
$conn->real_escape_string($variable);
For example,
$conn->real_escape_string($this->Lengte_update);
You're using the object-oriented style, so you can't use the procedural escape function. See the docs on mysqli::real_escape_string.
Edit:
The query isn't being executed. You assign the query to $query, but you need to call
$conn->query($query);
For anything to happen in the database.

PHP next MySQL row - how to move pointer until function checks true?

I have a PHP script which takes a value from a row in my MySQL database, runs it through a function, and if it determines it's true returns one value, and if it's false, it needs to go to the next value in the database and check that one until eventually one returns true.
I think I need to use mysql_fetch_assoc, but I'm not really sure in what way to use it... I wish I could post my code to be more specific, but it's a lot of code and most of it has no bearing on this issue...
Is the "function" something you could do in the database instead? It's really inefficient to process every row in the table to check for some type of condition. That's exactly what databases are good at, namely, processing queries efficiently and getting answers to you quickly.
So I'd recommend looking at how to do it all on the database side so that your PHP code is just fetching the end result (i.e. rows filtered by the function). Maybe if you provide more details of what your "function" is doing, a more specific answer can be provided.
You can use mysql_fetch_array, and just jump on the values fetched using $row[id] and not $row['name'].
Say your function returns true, you'd just use $row[lastid+1].
If the ID isn`t incremental, this could work :
$qry_result = mysql_query($qry) or die(mysql_error());
while ($row = mysql_fetch_array($qry_result)) {
$result = yourfunction($row['whatever');
if ($result != false)
break;
}
Also there is a php function next() which advances a pointer to the next array element. In your function you could implement an array builder, and then cycle between the elements with this. Depends on what your function actually does or script purpose is. It could lead to some load if there are alot of results.
You should not check database this way, as mentioned above. Database has a little difference from the plain text file.
You should not have a field in your database that has a bunch of values separated by value1:value2|value1:value2|value1:value2. It must be separate fields. Database has a little difference from the plain text file and you better learn it.
You could try something like this:
SELECT *
FROM table
WHERE field NOT LIKE '%$sessionvar:%';
I think that is what you are after?

Categories