[PHP][Mysql] Select and show simple - php

#GET from Mysql
$select = "SELECT content from content WHERE page = 'index';";
$result = mysql_query($select);
$row = mysql_fetch_row($result);
#Show in diferent places in my page
<?PHP echo $row[0]; ?>
<?PHP echo $row[1]; ?>
I'm using this code above, the problem is:
It's showing only the first result. What did I wrong?

$select = "SELECT content from content WHERE page = 'index';";
$result = mysql_query($select);
//$row = mysql_fetch_row($result);
// mysql_fetch_row() fetches ONLY ONE ROW
// If you want to fetch them all, yes, you must use a loop.
while ($row = mysql_fetch_row($result)) {
$rows[] = $row;
}
// So do this, get all the rows, and then you can use them in different places in your page
// Show in diferent places in your page
<?PHP echo $rows[0][0]; ?>
<?PHP echo $rows[1][0]; ?>

It's better to do this in a for loop - that way it will get all the results each time, rather than hardcoding for a scenario with just two results, etc.
<?php
$select = "SELECT content from content WHERE page = 'index';";
$result = mysql_query($select);
$rows = mysql_fetch_assoc($select);
foreach ($rows as $row) {
echo $row['content']; // associative array with strings for keys
}
?>
Also, you should be using mysqli for security reasons.

Related

How to get all entries out of a table?

I'd like to build a ul by pull the content out of a SQL table. But this code does only gives me the first row. What would be the best solution to get all 10 entries?
$query = "SELECT * FROM `activitys`";
echo '<td><ul>';
if ($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo "<li>".$row['content']."</li>";
}
echo '<td><ul>';
You need to put it in a loop, like this:
while($row = mysqli_fetch_array($result)) {
echo "<li>".$row['content']."</li>";
}
Wrap it in a while loop. That way it will keep going until the end. An IF only runs once.

Array for a SQL database using PHP

Can someone please help? I'm new to PHP and struggling to make this bit of code to work. For example I have a sql database table with the following schema and data:
Type....rent_price
a..........100
b..........200
c..........300
I want to be able to echo say, "a", in one section and "200" in another. The following code will display "a" but then I can't seem to get it to display anything from the rent_price column using a second array.
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['type']);
for ($set1 = array (); $row = $result->fetch_assoc(); $set1[] =$row['rent_price']);
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
You loop through the results twice, without resetting. Try to loop only once:
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
$set = array ();
$set1 = array ();
while ($row = $result->fetch_assoc())
{
$set[] = $row['type'];
$set1[] =$row['rent_price'];
}
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
Depending on what you mean by '"a" in one section and "200" in another', you may be able to forgo creating the intermediate arrays and just print the values from your query as you fetch them. Two cells in a table row, for example:
while ($row = $result->fetch_assoc()) {
echo "<tr><td>$row[type]</td><td>$row[rent_price]</td></tr>";
}
your data is in the first element of array
$set1[0]
but youre probably better off maintaining the naming throughout
$results = array();
while ($row = $result->fetch_assoc()){
$results[] = $row;
}
foreach ($results as $result){
echo $result['type'];
echo $result['rent_price'];
}
OR
$results = array();
while ($row = $result->fetch_assoc()){
$results['types'][] = $row['type'];
$results['rent_prices'][] = $row['rent_price'];
}
foreach ($results['types'] as $type){
echo $type;
}
foreach ($results['rent_prices'] as $rent_price){
echo $rent_price;
}

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

Something is wrong with my custom php function

Okay so I am trying to create a custom function that will echo a site url inside an iframe for the end user.
The script has to check whether or not the user has already seen the site and if they have seen it don't display it any more, but take another site url from the database etc.
Here's what I have come up with so far:
function get_urls() {
require 'config.php';
global $con;
global $currentUsername;
$con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
$query = "SELECT site_url FROM sites WHERE site_url IS NOT NULL";
$result = mysqli_query($con, $query);
// Get all the site urls into one array
$siteUrls = array();
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row;
$index++;
}
$query2 = "SELECT site_url FROM views WHERE user = '$currentUsername' AND site_url IS NOT NULL";
$result2 = mysqli_query($con, $query2);
// Get urls the user has already seen into another array
$seenUrls = array();
$index = 0;
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2;
$index++;
}
// Compare the two arrays and create yet another array of urls to actually show
$urlsToShow = array_diff($siteUrls, $seenUrls);
if (!empty($urlsToShow)) {
// Echo the url to show for the iframe within browse.php and add an entry to the database that the user has seen this site
foreach ($urlsToShow as $urlToShow) {
echo $urlToShow;
$query = "INSERT INTO views VALUES ('', '$currentUsername', '$urlToShow')";
mysqli_query($con, $query);
break;
}
}
// Show the allSeen file when all the ads are seen
else {echo 'includes/allSeen.php';}
mysqli_free_result($result);
mysqli_close($con);
}
I have currently found two errors with this. First the $siteUrls and $seenUrls are all okay, but when I compare the two using array_diff then it returns an empty array.
Secondly the script doesn't write the site url into the database because the $urlToShow is an array not a single url?
I think the problem is in your code is at the place where you are creating your $siteUrls, $seenUrls arrays. mysqli_fetch_assoc() function will give you a result row as an associative array. So if you want to change some of your code in the while loops.
Please chnage this
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row;
$index++;
}
To
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row['site_url'];
$index++;
}
And in the second while loop also. Change this
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2;
$index++;
}
To
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2['site_url'];
$index++;
}
and try
i would not run two queries and try to merge the result array. you can use mysql itself to just return the sites that have not been seen yet:
SELECT sites.site_url FROM sites
LEFT JOIN views ON views.site_url=sites.site_url AND views.user='$currentUsername'
WHERE sites.site_url IS NOT NULL AND views.site_url IS NULL
This will return only site_urls from sites, that have no entry in the views table. The LEFT JOIN will join the two tables and for every non-matching row there will be NULL values in the views.site_url, so that is why i am checking for IS NULL.
Your saving of $urlToShow should work, if you set to $row field content and not $row itself as suggested, but if you want to check what is in the variable, don't use echo use this:
print_r($urlToShow);
If the variable is an array, you will see it's content then.
#Azeez Kallayi - you don't need to index array manually.
$seenUrls[] = $row2['site_url'];
In addition, you can fetch all result
$rows = mysqli_fetch_all($result2,MYSQLI_ASSOC);
foreach($rows as $row){
echo $row['site_url'];
}

Filed name appearing on same line

Some code to fetch the field names by connecting it with db:
<?php
#mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM sample");
$storeArray = Array();
while ($row = mysql_fetch_array($result)) {
if (mysql_num_rows($result) > 0) {
$storeArray = $row['name'];
echo $storeArray;
}
}
?>
The above code works just fine but when it runs it gives me ramuraja. Here ramu and raja are seperate fields. But its giving me a joined output.
How can i get the two field value seperately like ramu and raja.
You print / echo the values directly after one another. Using echo $storeArray.'<br>'; would print a linebreak additionally, thus printing
ramu
Raja
However, you could also store all the variables in an array, for example with $storeArray[] = $row['name']; instead of $storeArray = $row['name'];. That would create a new array element, the value being $row['name'], while the key is incrementing for every element being added.
After having received all rows that match the query, you could loop through the array and Display the answers.
EDIT: Please check out mysqli or PDO; those PHP extensions are standard with newer versions and should be used instead of the old (and now deprecated) mysqli solution. Don't worry, they can do the same (and much more).
You need to do a for each statement to iterate through the array and echo the field along with a line break
First of all, you're declaring $storeArray as an array in this line: $storeArray = Array();, but later you replace it with a string $storeArray = $row['name'];
If you want to use $storeArray as an array, change this line:
$storeArray = $row['name'];
into
$storeArray[] = $row['name']; //add element to the array
Now loop all the results (remove echo $storeArray;)
After you've fetched all the results you kan echo them like:
foreach($storeArray as $name){
echo $name.'<br>';
}
Some confusion in code ....
first check ifthere are results:
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
....
}
}
than be more clear about what you wont:
an array :
$storeArray = Array();
or a string:
$storeArray = $row['name'];
I would so like this:
$storeArray = Array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$storeArray[] = $row['name'];
}
}
// array
print_r($storeArray);
// string
echo implode(',', $storeArray);

Categories