Getting data from MySQL through PHP - am I doing it right? - php

Simple question I guess, but a fundamental one and I'm not sure of the best practice.
So let's say that I have a database with some IP addresses that I want to display to the user.
Is this a good/secure way/practice?
//--> CONNECT TO DB, etc
$db_query = 'SELECT ip,'
."FROM table "
."GROUP BY ip ";
$result = $db_conn->query($db_query);
echo 'Found '.$result->num_rows.' records';
if($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQLI_BOTH))
{
//POPULATE A HTML TABLE/WHATEVER WITH THE INFO
}
}
I'm mostly concerned about this: $result->num_rows > 0 and this: fetch_array(MYSQLI_BOTH)
I'm asking because I read somewhere that num_rows > 0 can usually mean trouble depending on the situation, for example a user login. In that case I suppose it would num_rows == 1 right?
And also, I haven't fully understood the difference between MYSQLI_BOTH and other forms of fetching.. If you could simple explain them to me and when to use them I would be grateful.
What do you think?

I would add a check to ensure your query was executed OK - and if not output the error :
$result = $db_conn->query($db_query);
// check for error - output the error
if (!$result) {
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $db_query;
die($message);
}
echo 'Found '.$result->num_rows.' records';
Other than that ... looks OK
EDIT:
To explain MYSQLI_BOTH, the options are MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH ->
MYSQLI_ASSOC = Associative array so the value of the rows can be accessed using $row['column']
MYSQLI_NUM = Numeric array so the values of the rows are accessed using a number $row[n] where n is the number of the column (0 based)
MYSQLI_BOTH = can use both to access values of row either $row[n] or $row['column']
EDIT2:
There is also a function for checking the number of returned rows :
if(mysqli_num_rows($result) == 0){
echo "Sorry. No records found in the database";
}
else {
// loop you results or whatever you want to do
}
EDIT3:
php.net has some excellent docs for the MY_SQLI extension

Two things:
If you only need an associative array, then don't use fetch_array(). Use fetch_assoc().
There's no need to concatenate the query like that, you could use something like:
$sql = "
SELECT
ip
FROM
table
";
This helps with large queries with multiple options in the WHERE clause or JOINs. It's quicker to type out, and you can quickly copy and paste it for checking in phpMyAdmin and the like.

Related

Query more slow

I do a query but does not show anything on the screen and when I opened the page where I do the query is slow and does not show anything
$query="SELECT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result = mysqli_query($conne,$query);
while($row=mysqli_num_rows($result)){
echo $row['COMPONENTE'];
}
mysqli_num_rows() will only use for getting no of rows not for row data.
You need yo use mysqli_fetch_*()
while($row=mysqli_fetch_array($result)){
echo $row['COMPONENTE'];
}
Why this query slow? Because you are using infinite loop here, always TRUE.
while($row=mysqli_num_rows($result))
One more story, I hope you are using session_start() in your file, but suppose that if $_SESSION not found or not start than your query will failed.
In last, this is just a suggestion regarding Naming Convention, you are using column name in small letter, capital small, full capital, this is not related to answer but you must need to learn about this art.
this will help you to understand Naming Convention: Database, Table and Column Naming Conventions?
This reference will help you to understand how mysqli_fetch_array() works: http://php.net/manual/en/mysqli-result.fetch-array.php
Please try with this one for return value and if you need number of raw then the statements will be different.
$query="SELECT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result = mysqli_query($conne,$query);
while($row=mysqli_fetch_array($result)){
echo $row['COMPONENTE'];
}
As others have pointed out, you have mixed up the mysqli_num_rows function, here I am using it to print the number of results found, then loop through the results after converting the mysqli result object to an array named $row
echo 'Found '. mysqli_num_rows($result) .' results';
while ($row = mysqli_fetch_array($result)) {
echo $row['COMPONENTE'];
}
You are fetching record but using mysqli_num_rows() which return total number of rows/records replace it with mysqli_fetch_array() here is the working example.
$query="SELECT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result = mysqli_query($conne,$query);
while($row = mysqli_fetch_array($result)) { //replace mysqli_num_rows with mysqli_fetch_array
echo $row['COMPONENTE'];
}

How do I echo the contents of a MySQL table field?

I seem to be having trouble understanding the concept of how to properly use the information in a MySQL database using PHP/MySQLi. As I understand it, you generate a variable representing the connection object:
$connectionObject = mysqli_connect('serverString', 'userString', 'passString', 'databaseString');
then, generate a variable representing the query string you want to use:
$queryString = "SELECT rowName FROM tableName";
then, generate a variable representing the result object returned from a successful query:
$resultObject = mysqli_query($connectionObject, $queryString);
then, you use the fetch_assoc() function to generate an array from the result object and assign it to a variable:
$resultArray = myqli_fetch_assoc($resultObject);
then, you can use a while loop to (I have trouble with this one) to sort through the array and use the content of the row somehow:
while ($resultArray) {
echo $resultArray["rowName"];
}
Do I have this concept the wrong way, somehow, because its just not working for me, even to output the text content of a text-based CHAR(10) field with the contents of no more than: "BLAH".
The need to loop through the array to pick out the array item by name in the end anyway seems moot to me to begin with, but no matter where I look, I find the same concept.
My script code, minus a few key details, is:
if ($connectionObject=mysqli_connect("host0", "username0", "password0", "mysqldatabase0")) {
echo "Con";
}
if ($queryString="SELECT 'testdata' FROM 'testtable'") {
echo "Query";
}
if ($resultObject=mysqli_query($connectionObject, $queryString)) {
echo "Result";
}
if ($resultArray=mysqli_fetch_assoc($resultObject)) {
echo "Array";
}
while ($row=$resultArray) {
echo $row["testdata"];
print_r ($row);
}
mysqli_fetch_assoc returns an associate array of string representing the fetched row in the result set which is your $resultObject.
The problem is where you're using the while loop. You want to capture the returned associative array in a variable and access your data via that variable like follows:
while ($row = $resultArray) {
echo $row["rowName"];
}
To sort by rowName you can use the mysql order by clause in your query like follows which returns your results sorted by rowName:
$queryString = "SELECT rowName FROM tableName order by rowName";
Update after OP posted full code:
In your first if statement what would happen if the connection failed? You want to add some error handling there:
$connectionObject=mysqli_connect("host0", "username0", "password0", "mysqldatabase0"));
if (!$connectionObject) {
// exist out of this script showing the error
die("Error connecting to database " . mysqli_error($connectionObject));
} else {
// Don't really need this else but I'll keep it here since you already had it
echo "Con";
}
The problem is here You are using single quotes for column name and table name which are mysql identifiers. MySQL identifiers quote character is backtick not single quote.
Basically you need to use backticks if one of these identifiers are one of mysql reserved words (MySQL Reserved words), for other cases you don't need to use them.
Update your query:
if ($queryString="SELECT `testdata` FROM `testtable`") {
echo "Query"; // Leaving as is, not required
}
Lastly, an improvement. You want to add error handling here too:
if ($resultObject=mysqli_query($connectionObject, $queryString)) {
echo "Result"; // Leaving as is, not required
} else {
echo "Error executing Query " . mysqli_error($connectionObject);
}
Please note that when you use this script the error messages will be printed at the client i.e. when you use this script in a web application the errors will be shown in the user's browser. So you want to look into implementing logging and not printing them directly.
mysqli_fetch_assoc() returns one row as an associative array, of a mysqli_result object. Each time it is called, it returns the next row of results automatically and when used with a while loop, can be used to fetch an unknown number of result rows.
The $row['columnName'] is used to refer to the column. For example, if you had a person object with columns firstName, lastName, dateOfBirth, you could iterate through each person with a while loop as such:
while($row=mysqli_fetch_assoc($resultObject)){
$fname = $row['firstName'];
$lname = $row['lastName'];
$dob = $row['dateOfBirth'];
echo $fname . ' ' . $lname . ' ' . $dob;
}
This will echo details for a result returning an unknown amount of people.
Remember, calling the
if ($resultArray=mysqli_fetch_assoc($resultObject)) {
echo "Array";
}
before the while loop will skip the first result, so make sure the query returns multiple results when testing, as if you are only providing a resultObject containing one result, this might be why it isn't returning anything.
A better way to check if any results are returned is with the mysqli_num_rows($resultObject) function.
if(mysqli_num_rows($resultObject) > 0){
echo "Array";
}
Also not sure if it was just a typo but just to be sure, in your query you are selecting columnName not rowName:
$queryString = "SELECT columnName1(eg. firstName), columnName2(eg. lastName) FROM tableName";
I just recently started learning PHP, and the mysqli_fetch_assoc function confused me too, so I hope this helps!

echo statement not showing result after getting variable from $_post in php mysql

I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.

Count specific row in MySQL

If I want to count one specific row (unread) in my database, how should i proceed with this MySQL query? As of now it counts the whole table.
$result_notifications = mysql_query("select count(1) FROM bhost_notifications where taker_id='$user_info[u_id]'");
$row_notifications = mysql_fetch_array($result_notifications);
$total_notifications = $row_notifications[0];
You need to alias the column.
SELECT COUNT(1) AS count ...
Then you would call $row_followers[count]. Be aware that mysql_ functions are deprecated. Learn about prepared statements when passing variables, and use PDO or MySQLi - this article will help you decide which.
I suspect you have an un-normalized database. While that is preferable in some situations, I doubt that they are in yours. As written you cannot be sure that the query will return the row you desire. SQL does not guarantee the order of rows, unless you use an order by clause.
It seems like this question indicates more problems the some syntax issues.
Over time I have written a nice function in PHP that allows me to easily look up records but still be dynamic enough to be useful in every type of query that I perform.
Usage:
if (get("select * from table", $query_array) > 0)
{
// There is at least one row returned
$result_array = mysql_fetch_array($query_array);
.
.
.
} else {
// No rows in the set
}
Function:
function get($sql, &$array)
{
$array = "";
$q = mysql_query($sql);
if (mysql_error())
{
$ret = -1;
print "<div><font style='font-family: arial; font-size: 12px;'><font style='color: red;'>Error:</font> " . mysql_error() . "<br>SQL: #sql</font></div>";
exit(1);
} else {
$ret = mysql_num_rows($q);
if ($ret > 0)
{
$array = $q;
}
}
return $ret;
}
This also gives a formatted error message in the case that there is something wron with the query. I use this all the time because it compresses the mysql_query and mysql_num_rows together into a single command.

Passing PHP MySQL Result Object to Function

I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);

Categories