MySQL query pulling one row and displaying first letter of result - php

I think I need a basic PHP / MYSQL refresh, because nothing is working for me.
My MYSQL Table has two rows of information.
$results = mysql_query("SELECT Name, Description FROM products");
$results = mysql_fetch_assoc($results);
print_r($results);
When printing this, all I get is one result. Array ( [Name] => Banana [Description] => It's a lovely banana ). There are definitely two results in the table. Why is this happening?
Secondly, this loop only returns the first letter of each result, and I don't know why!
foreach($results as $res) {
?>
Name : <?php echo $res['Name']; ?><br />
Description : <?php echo $res['Description']; ?><br />
<?php } ?>
My brain is seriously scrambled today :(

while($res = mysql_fetch_assoc($results)){
?>
Name : <?php echo $res['Name']; ?><br />
Description : <?php echo $res['Description']; ?><br />
<?php } ?>

MySQL has been deprecated and you should either move to PDO or MySQLi. To answer your question for the latter, you should use a prepared statement (although in this case it doesn't matter much since you don't need to sanitize the query)
$connection = new mysqli('localhost','root','pw','db');// start mysqli connection
$results = $connection ->prepare('SELECT Name, Description FROM products');// create the statement you want to work with
(object)array('Name'=>'','Description'=>'');// set up the variables you want to put retrieved data in
$results ->bind_result($res ->Name, $res ->Description);// attach the variables to the prepared statement
while($results ->fetch()){// execute the prepared statement
// perform actions with $res->Name and $res ->Description
}

To answer your first question, it is because mysql_fetch_assoc() only gets one row of data from the result set at a time. Typically, a while loop is used to gather all results like this:
$results = mysql_query("SELECT Name, Description FROM products");
$result_array = array(); // don't name this array the same as your result set ($results) or you will overwrite it.
while($row = mysql_fetch_assoc($results)) {
$result_array[] = $row;
}
I honestly don't know why you would only be echoing out the first letter of each field. Does it just appear that way on screen do to some problem with your HTML construct? In other words if you look at the HTML source, is it shown correctly?

Related

cannot retrieve indexes correctly mysqli

$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.

PHP MySQL Database - All rows into Multi-Dimensional Array

It's been a long while since I touched PHP so, I just need a refresher of sorts.
I have an HTML form that captures several lines of data (dataA, dataB, dataC & dataD) and inserts them into a database table (dataAll). I will be entering rows upon rows of data into "dataAll". What I'm looking to do is create a display.php page, where the code will take all of the data and place each cell into an array, or the row of an array, for example:
new Array = [["dataA", "dataA", "dataA", "dataA", "dataA"],
["dataB", "dataB", "dataB", "dataB", "dataB"],
["dataC", "dataC", "dataC", "dataC", "dataC"],
["dataD", "dataD", "dataD", "dataD", "dataD"]];
But I cannot remember the syntax on how to perform this task. Any help would be greatly appreciated.
The database is named 'compdata', the table is 'dataAll', and each row is 'dataA', 'dataB', 'dataC', 'dataD'.
Please let me know if I need to supply more information.
Since you asked for All rows, so the simple code for query is written below:
<?php
//after connection to mysql db using mysql_connect()
$sql = "Select dataA, dataB, dataC, dataD from `compdata`.`dataAll`" ;
$result = mysql_query($sql) ;
if(mysql_num_rows($result) > 0 ){
while($row = mysql_fetch_array($result)){
$dataArray[] = $row ;
}
}
echo '<pre>';
print_r($dataArray) ;//you got the desired 2D array with all results
?>
Assuming you are used to the old mysql_xxx functions:
$data = array ();
$result = mysql_query ('select * from dataAll');
while ($row = mysql_fetch_array ($restult, MYSQL_ASSOC))
$data [] = $row;
Result:
$data = array (
0=>array ('col_1'=>'dataA', 'col_2'=>dataB...),
1=>array ('col_1'=>'dataA', 'col_2'=>dataB...)
);
If you only want the numbers and not the column names, use MYSQL_NUM.
However, mysql functions are being replaced with the more generic PDO object so you might want to look into that.
$stmt = $pdo->query ('select * from dataAll');
$result = $pdo->fetchAll (PDO::FETCH_ASSOC); // Or PDO::FECTCH_NUM
Same results as above.

drilling down in PHP using hyperlinks

I am a novice at PHP and i have encountered a problem with the following code...
<?php
// Connects to Database
mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query("SELECT country_id, country_name FROM country, channels WHERE channels.channel_id = country.channel_id AND channels.channel_id = '1'")
or die(mysql_error());
echo "<table border=0 cellpadding=15>";
echo "<tr align = center bgcolor=white>
<td><b>Country ID</b></td><td><b>Country Name</b></td>" ;
while (mysql_fetch_row($data)) {
$cid = mysql_result($data, 1);
$cname = mysql_result($data, 2);
# inserts value into table as a hyperlink
echo "<tr align = center bgcolor=white><td>$cid</td><td><a href=view_country_detail.php?cid=$cid>$cname</td>";
}
# displays table
print '</table>';
?>
to explain the problem i am getting, i am after generated hyperlinks to drill down to the companies which share the to be clicked country's id from the code above to then display a similar layout on the 'view_country_detail' page. i cant work out why the output for the table gives me a repeated row for the first two id's for the country column in the db. any help would be greatly appreciated as i am totally lost here. Thanks
I don't understand why you use mysql_fetch_row and then don't want to actually use the row you fetch.
You should not be using mysql_result here. What you are doing is fetching data from row 1 of the result set and then data from row 2 regardless of which row the pointer is on in your while loop.
Try this:
while ($row = mysql_fetch_assoc($data)) {
$cid = $row['country_id'];
$cname = $row['country_name'];
}
I personally find it much more readable in code to reference the fields by the associative keys used when using mysql_fetch_assoc or mysql_fetch_array.
Try structuring your while loop as follows:
while($row = mysql_fetch_array($data)){
$cid = $row[0]; //if you have the column names, replace 0 with 'column_name'
$cname = $row[1];
//then echo statement
}
Also, mysql_* functions have started the deprecation process and should no longer be used, even the php manual pages state the use of mysql_* is discouraged. Look into using the similar mysqli_* functions or PDO.
Try this:
while ($row = mysql_fetch_row($data)) {
$cid = $row[0];
$cname = $row[1];
...
}
mysql_fetch_row returns an array.
HOWEVER
You should look at stopping using the mysql_* functions - they're being deprecated. If you switch to PDO or mysqli, it helps make your code more secure, too.

Mysql database retrieve multiple rows

I use a mysql database. When I run my query I want to be able to put each row that is returned into a new variable. I dont know how to do this.
my current code:
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution=$row['solution'];
}
?>
The thing is that check num rows can return a row of an integer 0-infinity. If there are more solutions in the database how can I assign them all a variable. The above code works fine for 1 solution, but what if there are more? Thanks.
You can't give each variable a different name, but you can put them all in an array ... if you don't know how this works I suggest looking at a basic tutorial such as http://www.w3schools.com/php/php_arrays.asp as well as my code.
A very simple way (obviously I haven't included mysql_num_rows etc):
$solutions = array()
while($row = mysql_fetch_assoc($result)) {
$solutions[] = $row['solution'];
}
If you have three in your result solutions will be:
$solutions[0] -> first result
$solutions[1] -> second
$solutions[2] -> third
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$solution = array();
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution[]=$row['solution'];
}
?>

Catch an array of data and outputting a single row

I need to have a single row of data "printed out" through php.
So, take this example from w3schools:
http://www.w3schools.com/PHP/php_mysql_select.asp
There is a cicle that goes through all the rows ( in this case, 2) and prints them out. The end result is:
Peter Griffin
Glenn Quagmire
What I want is to be able to select row 1 or 2 (or more) and just have that row of data selected. Then I could say something like (I know this doesent work, just an example):
echo $row["Name",2];
And get:
Glenn Quagmire
I believe I have to get a special parameter in mysql_fetch_array, but I cant find it anywhere, and I bet its something really simple. Please help me out, full examples/tutorials/guides links are preferred.
you have 2 options. First is edit your SQL query like exmaple below this will return just 2nd row from database.
$result = mysql_query("SELECT * FROM Persons" WHERE id = 2);
Or during the foreach loop fetch all result into another array.
$result = mysql_query("SELECT * FROM Persons");
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row['FirstName'] . " " . $row['LastName'];
}
As far as i know mysql doesnt have a function to return the entire query as an array.
So you can switch to using PDO (recommended):
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll();
echo $result[1]['name'];
or if you must use the mysql_functions just create an array with the loop:
while($row = mysql_fetch_array($result)) {
$result[] = $row;
}
echo $result[1]['name'];
fetchall the results into an array and print the row you want.

Categories