Array value to string in PHP - php

I've got some code which randomly fetches data from a database, but whenever I prints the data in the browser is looks like that - ["data"]. I want it to be a clear string. How can I make that? Thank you!
Here is the code:
<?php
require '../wordbeater/adminpanel/includes/dbh.inc.php';
$result=mysqli_query($con, "SELECT * FROM users ORDER BY RAND() LIMIT 6");
$count = 0;
while($row=mysqli_fetch_row($result)){
$postsarray["one.$count."] = $row[1];
$postsarray["two.$count."] = $row[2];
$count++;
}
$encodedArray = array_map(utf8_encode, $postsarray);
echo $encodedArray;
mysqli_close($con);
?>

Try using:
$result=mysqli_query($con, "SELECT * FROM users ORDER BY RAND() LIMIT 6");
$count = 0;
while ($row = $result->fetch_row()) {
$postsarray["one.$count."] = $row[1];
$postsarray["two.$count."] = $row[2];
$count++;
}

I think you should go for mysqli_fetch_assoc as it will give you the same associative array as like your database.
for e.g.
while($row=mysqli_fetch_assoc($result)){
$postsarray["one.$count."] = $row["column_name_u_want_to_fetch"];
$postsarray["two.$count."] = $row["2_column_name_u_want_to_fetch"];
$count++;
}

You can directly store it in a variable so it will take it as a string.
for e.g.
$stringone="";
$stringtwo="";
while($row=mysqli_fetch_assoc($result)){
$stringone.$count = $row["column_name_u_want_to_fetch"];
$stringtwo.$count = $row["2_column_name_u_want_to_fetch"];
$count++;
}
for($i=0; $i<mysqli_num_rows($result); $i++)
{
echo $stringone.$i;
echo $stringtwo.$i;
}

try it by removing 'ORDER BY RAND() LIMIT 6'

Related

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 to store a row into an array in PHP and echo out a certain value of the array?

I'm trying to query data from a row in a table, store the data into an array, and then echo out a certain value from the array. Here's the PHP:
$receiveuserdata = mysqli_query($connection, "SELECT * FROM s_users LIMIT 0,1");
$userdata = array();
$index = 0;
while ($row = mysqli_fetch_assoc($receiveuserdata)) {
$userdata[$index] = $row;
$index++;
};
I've tried using other posts related to this issue for help, but most are outdated. Here's my attempt to echo a value from the array:
<h3>Username: <?php echo $userdata[0]; ?></h3>
Am I using $receiveuserdata incorrectly?
To retrieve Single row
You are used to LIMIT 0,1 - so it will retrieve only one row
<?php
$receiveuserdata = mysqli_query($connection, "SELECT * FROM s_users LIMIT 0,1");
if (mysqli_num_rows($receiveuserdata) > 0)
{
$row = mysqli_fetch_assoc($receiveuserdata);
$username = $row['username'];
echo '<h3>Username: '.$username.'</h3>';
}
?>
To retrive multiple rows
<?php
$receiveuserdata = mysqli_query($connection, "SELECT * FROM s_users");
if (mysqli_num_rows($receiveuserdata) > 0)
{
while ($row = mysqli_fetch_assoc($receiveuserdata)) {
$username = $row['username'];
echo '<h3>Username: '.$username.'</h3>';
}
}
?>
$row contains the entire MySQL table row. Which means that $userdata[0] also contains a row (as an associative array). Using echo does not work with arrays. Instead you can use var_dump if you want to see what the row is or access the value you need directly: $userdata[0]['username'] (if you have a column name username)

I've some issues with an array $row fetched from MySQL

I've some issues with an array fetched from MySQL
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
mysql_fetch_row($result);
echo $row[0]; // doesn't work
echo $row[1]; // doesn't work
but this work
echo $row["FirstFieldName"] //OK
...
how should I change the following code to make it work?
for ( $i = 0; $i < count( $row ); $i++ )
{
echo $row[ $i ];
}
thanks
Do below changes. use mysql_fetch_array instead of mysql_fetch_row()
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
$row=mysql_fetch_array($result);
for ( $i = 0; $i < count( $row ); $i++ )
{
echo $row[ $i ];
}
Try using mysql_fetch_array() instead.
The three functions you should look into are:
mysql_fetch_row,
mysql_fetch_array, and
mysql_fetch_assoc
Each does things a little differently.
Try it this way:
$sql = "SELECT id,email FROM people WHERE id = '42'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row[0];
}
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
$row=mysql_fetch_array($result);
echo $row[0];
echo $row[1];
it will work
mysql_fetch_row returns one row, so to be able to use it you should do :
while( $row = mysql_fetch_row( $result ) )
{
echo $row["email"];
}
Otherwise, as Mike said you should use mysql_fetch_array()
ie.... this takes all the retrieved keys/fields and intereates them and hands them off to $s which can then be placed into html..
foreach($row as $key=>$val){
$$key = $val;
$s.= "<tr><td>".$key."</td><td>
<input type=text size=88 name='".$key."' value='".$val."'></td></tr>";
}
// end your php then onward to html
<table>
<?php echo $s;?>
</table>

Generating variables from db content?

I am querying a database to get 6 values in my params table suing this;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$param = $row['value'] ;
}
is this right, if so is their away i can add one to the variable name each time round so i get $param1, $param2....
I dont want to have to send a query to the database for each param, is it possible to get them all like this?
The simpliest way is to use an array:
$result = mysql_query("SELECT * FROM params");
$param = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$param[$i] = $row['value'] ;
$i++;
}
Than you get $param[0], $param[1], ...
You can create variable names like this:
${'var'.1}
${'var'.'1.cat'}
${'var'.$x}
${$y.$x}
and so on.
This seems like a design flaw. But what you can do is:
$count = 1;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$paramname = 'param' . $count++;
$$paramname = $row['value'] ;
}
You may find the list function useful - http://php.net/manual/en/function.list.php
list($param1,$param2,$param3,$param4,$param5,$param6) = mysql_fetch_row($result);
Probably more use when using descriptive variables, just a thought.

php mysql query if $num_results > 0

I want to make a php search query.
First put a sentence and explode every word get $name.
Then I put $name make a query to match all the name which exist in my database.
How to use a if ($num_results > 0) if I am not sure how many $name are matched and echo out?
(may be $row['name'] is null, maybe $row['name'] is 1 or 2, I want to get them one by one)
$query = mysql_query("SELECT * FROM books
WHERE name LIKE '$name[0]' OR name LIKE '$name[1]' OR name LIKE '$name[2]'
OR name like '$name[3]' ");
while ($row = mysql_fetch_array($query)) {
if ($num_results > 0) {
echo $row['name'][0] ;
}
if ($num_results > 1) {
echo $row['name'][1] ;
}
if ($num_results > 2) {
echo $row['name'][2] ;
}
if ($num_results > 3) {
echo $row['name'][3] ;
}
}
use:
mysql_num_rows($query);
to get the amount of rows you get from your mysql query
<?php if (mysql_num_rows($query)>0){?>
Do stuff
<? }else{ ?>
We didn't find anything!
<?php }?>
How about:
$i = 0
while($row = mysql_fetch_array($query)) {
echo $row['name'][$i];
$i++;
}
I didn't actually understood what you really want but your code should make more sense like this:
<?php
$searchphrase="alex nick george";
// this:
$names = explode(" ",$searchphrase);
// produces the following:
$names = array("alex","nick","george");
// so you can make the query:
if(is_array($names)){
$query = "SELECT * FROM books WHERE name IN ('".implode(",",$names)."') ORDER BY FIELD (name,".implode(",",$names).")";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0){
// no results
}else{
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
}
}
}
?>
Perhaps if you describe it better we can help more efficiently.

Categories