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!
Related
I need to be able to check and see in a certain string is anywhere within my SQL table. The table I am using only has one column of char's. Right now it is saying that everything entered is already within the table, even when it actually is not.
Within SQL I am getting the rows that have the word using this:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
However, in PHP the word is being entered by the user, and then I am storing it as a variable, and then trying to figure out a way to see if that variable is somewhere within the table.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
You need to do a little bit more than building the query, as mysql_query only returns the resource, which doesn't give you any information about the actual result. Using something like mysql_num_rows should work.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
Note: the mysql_* functions are deprecated and even removed in PHP 7. You should use PDO instead.
In the SQL you used
%streeetName%
But in the query string below, you used
%$streeetName%
Change the correct one
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
if($results->num_rows) is what you need to check if you have results back from your query. An example of connection and query, check, then print or error handle, the code is loose and not checked for errors. Best of luck...
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }
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.
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.
i'm having a strange problem with php + recordsets.
my code:
$rc = mysql_query("select * from myTable",$db);
if (!$row = mysql_fetch_assoc($rc))
{
$eof=true;
}else{
echo "there is data!<br>";
$rs = mysql_fetch_array($rc);
echo $rs[id];
echo $rs[txt];
}
the strange thing - the query is correct - it's echoing "there is data" but when echoing the actual field values returns empty strings .. :(
any ideas what could be wrong?
In your else block, you are re-fetching some data from the database, using mysql_fetch_array().
But a first row has already been fetched earlier, by mysql_fetch_assoc().
So, basically :
In the if's condition, you are fetching a first row
If it succeed, you enter the else block
where you try to fetch a second row
and using the returned (or not) data, without testing the success of that second fetch.
You should probably do only one fetch -- using either mysql_fetch_assoc or mysql_fetch_array -- but not two.
you already fetched data, use mysql_num_rows() instead
$rc = mysql_query("select * from myTable",$db);
if (mysql_num_rows($rc))
{
echo "there is data!<br>";
$rs = mysql_fetch_array($rc);
echo $rs[id];
echo $rs[txt];
}else{
$eof=true;
}
Be consistent in your use of if mysql_fetch_assoc($rc)...
$rs = mysql_fetch_array($rc);
will return an enumerated array, so $rs['id'] doesn't exist only $rs[0], $rs[1], etc.
Use
$rs = mysql_fetch_assoc($rc);
to return an associative array with $rs['id']
Your first test also fetches and discards a row
And quote the indexes in $rs: $rs['id'] rather than $rs[id]
i have function which is something like this
function multiple_delete($entity1,$entity2,$entity2) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $entity1;
echo $entity2;
echo $entity3;
}
and my function call is
multiple_delete('$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
keeping in mind the three value which i am passing through the parameter is the entity name of particular table.
now this function will print it as the string i.e ($row['pic_title'], $row['pic_brief']', $row['pic_detail']) and hence not parse it as the value which i want it to do. if it parse it as the value then i will be able to get the records from the database. i have tried with the combination of single quotes, doubles, with concatenation operator etc. is there any way i tell the script that do not parse it as the string instead treat it as it have been declared to fetch the value from database. does php have any function for this ? or i am going wrong with the logic.
if i skip the parameters and declare in the functions something like this.
echo $row['pic_title'];
echo $row['pic_brief'];
echo $row['pic_detail'];
it works perfectly fine . why is that when i try to achieve the same thing with the help of parameter it refuses to fetch the value from the database, and instead it returns the same declared string from the function call.
Please do not tell me that i dont need that parameter, i need it because i want it to perform the dynamic data manipulation, with regard to different tables and different table entities. and the above function is just the demonstration of my problem not the exact function. if you want to have a look at the exact function you can check here.
What is wrong with my function?
thank you
Just pass the names of the columns:
multiple_delete('pic_title', 'pic_brief', 'pic_detail');
Then you can use them to access the corresponding values in the row array by using the names them as keys:
function multiple_delete($entity1, $entity2, $entity3) {
$query = "SELECT * FROM tablename WHERE id = '4' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[$entity1];
echo $row[$entity2];
echo $row[$entity3];
}