Storing the result of an SQL call in a php variable - php

I have the code below and it's working as it should however instead of echoing the results to the screen, I need to store the results in a php variable called $var. How would I go about doing that?
<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";
$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db");
$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {
echo $row['id_member'];
}
mysql_close($con);
?>

Depending on what you want to achieve here is a few possible ways of doing this
$var = "";
while ($row = mysql_fetch_array($result)) {
$var .= $row['id_member'] . "\n";
}
$var = array();
while ($row = mysql_fetch_array($result)) {
$var[] = $row['id_member'];
}

replace echo with $var[].
That will push each result onto the end of the array. It would probably be good to define the variable first.
$var = array();
while ($row = mysql_fetch_array($result)) {
$var[] = $row['id_member'];
}

<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";
$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db");
$result = mysql_query($sql, $con);
$v = array(); // $v instead of $var, since var is a keyword and may cause troubles
while ($row = mysql_fetch_array($result)) {
array_push($v, $row['id_member']);
// or
//$v[] = $row['id_member'];
}
mysql_close($con);
?>

If the select statement will return more than one result, then you need to store the values in an array:
$member_ids = array();
while ($row = mysql_fetch_array($result)) {
$member_ids[] = $row['id_member'];
}
If the select statement will return a single result (you can make sure by appending a LIMIT 1 to the value of the $sql variable).
$row = mysql_fetch_array($result);
$member_id = $row['id_member'];

Related

While loop is printing two times output

In my code, while loop is printing two times output. Here is my PHP code:
if($con)
{
echo '<h1>Connected to MySQL</h1>';
$sql = 'select age, salary from emp';
mysql_select_db('toor');
$retval = mysql_query($sql, $con);
if(!$retval)
die('could not get data'.mysql_error());
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{
echo "age:{$row[0]}<br>"."sal:{$row[1]}<br>";
}
}
Replace
$row = mysql_fetch_array($retval, MYSQL_NUM)
with
$row = mysql_fetch_array($retval)
and remove $con from mysql_query()

implode output does not gives proper output

This shows all the elements from an array in a string but without a separator. I used ',' as a separator in this code. And it does not work. How can i separate them with separator.
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Database Connection failed.".mysql_error());
}
$db = mysql_select_db("test1",$con);
if(!$db)
{
die("Database selection failed.".mysql_error());
}
$query = "select * from menu limit 10";
$result = mysql_query($query,$con);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
//$menu_name = $row['m_name'];
//$menu_image = $row['m_image'];
$menu_name = array($row['m_name']);
$menu_image = array($row['m_image']);
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
}
if(!$result)
{
echo mysql_error;
}
?>
you are storing array into variable . so if you will use imploade on an variable it will not show the result so best way is to store your result into an array and then use implode .
Don't use depricated mysql_* function use mysqli_* or pdo
instead
$menu_image=array(); // start array to store
$menu_name=array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name']; // store menu name
$menu_image[] = $row['m_image']; // store menu image
}
echo implode(',',$menu_name); // finaly use implode
You can try this:
$menu_name[];
$menu_image[];
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$menu_name[] = $row['m_name']; // I change your $menu_name into an array so that when you fetch $row['m_name'] it returns an array
$menu_image[] = $row['m_image']; //same thing
}
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
try this in place of your while loop
$menu_name = array();
$menu_image = array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name'];
$menu_image[] = $row['m_image'];
}
echo implode(',',$menu_name);

Mysql parameterized queries in php

I have a php code for some MYSQL interogations,
Code is:
$DBTYPE = 'mysql';
$DBHOST = 'localhost';
$DBUSER = 'tuser';
$DBPASSWORD = 'password';
$DBNAME = 'dbname';
$link = mysql_connect($DBHOST, $DBUSER, $DBPASSWORD);
mysql_select_db($DBNAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//IMG**0**
$hotelc = $hotelCodes[**0**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**0** = $row["ImageURL"];
}
//IMG**1**
$hotelc = $hotelCodes[**1**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**1** = $row["ImageURL"];
}
..........................
//IMG**x**
$hotelc = $hotelCodes[**x**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**x** = $row["ImageURL"];
}
The repeating value on each code line is bolded.
How can i create a Mysql parameterized queries in php.n to avoid write all the lines .I need to extract ~100 $ImageURL from the Flat_table where the $hotelc is found.
For example you have to repeat it $N times:
for($i=0; $i<$N; $i++)
{
$hotelc = $hotelCodes[ $i ];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: ".mysql_error());
}
while ($row = mysql_fetch_array($result)) {
${'ImageURL'+$i} = $row["ImageURL"];
}
}
To loop, use for:
for($n=0; $n<100; $n++){
$hotelc = $hotelCodes[$n];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL[$n] = $row["ImageURL"];
}
}
But the inner functions inside the loop is inefficient because mysql query will be executed 100 times. You can query all the ImageURL by using IN() syntax in mysql:
//Wrap all hotelCodes into one string for query, like ["a","b"] to "'a','b'"
$len = count($hotelCodes);
foreach($hotelCodes as $key=>$code){
$hotelCodes[$key] = "'".$code."'";
}
$codesStr = implode(",", $hotelCodes);
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode IN (".$codeStr.")", $link);
//Other things...
When writing a function, you look for the commonality. Furthermore, you want to minimize the database interaction. I am, for the sake of deprecation, going to assume $link uses mysqli_connect()
$ImageURL = array();
$list = implode('", "', $hotelCodes);
$result = mysqli_query($link, 'SELECT ImageURL FROM Flat_table where HotelCode IN "' . $list . '"');
while($row = mysql_fetch_assoc($result)) {
$ImageURL[] = $row["ImageURL"];
}
This runs only one query and then loops through the results, generating an associative array. So echo $ImageURL[0]; will output your first URL.

Store Column Values in Array

I'm trying to store the title(summary) and date(created) of an event in an array. But I think im missing something in my loop.
<?php
$summary = array();
$date = array();
mysql_connect('mysql.server', 'myUsername', 'myPass') or die('Could not connect: ' . mysql_error());
mysql_select_db("mxgsite") or die(mysql_error());
$query_summary = mysql_query('SELECT summary FROM event_info') or die(mysql_error());
$query_date = mysql_query('SELECT created FROM event_details') or die(mysql_error());
$row_summary = mysql_fetch_array($query_summary);
$row_date = mysql_fetch_array($query_date);
$i = 0;
while(($row1 = mysql_fetch_array($query_summary))) {
$row2 = mysql_fetch_array($query_date);
$summary[] = $row['summary'];
$date[] = $row['created'];
echo $summary[$i] . " " . $date[$i] . "<br ?>";
$i++;
}
I know i'm getting values because I can echo out 1 value, but if I want to put all the values in an array and try to echo out that array I keep getting blank values?
It seems to me like you are trying to do too many things here. Since the 2 sets of values are not being stored in a way where they are related/linked to each other, you might as well deal with them in separate while loops. Try something like this:
while ($row = mysql_fetch_array($query_summary)){
$summary[] = $row[0];
}
while ($row = mysql_fetch_array($query_date)){
$date[] = $row[0];
}
If you want to relate the tables, per the comments above, you can try something more like:
$result = mysql_query('SELECT a.eventid, a.summary, b.created
FROM event_info a
join event_details b
on a.eventid = b.eventid');
$events = array();
while ($row = mysql_fetch_array($result)){
$event = array();
foreach ($row as $key=>$value){
$event[$key]=$value;
}
$events[] = $event;
}

How do I output certain index values from a foreach array?

This is the structure in the database:
items |itemLink
----------------------
Kill Bill|Kill Bill link
Preman |Preman link
This is the code:
$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$items = 'SELECT items FROM menus';
$itemLink = 'SELECT itemLink FROM menus';
$itemQuery = $db->query($items);
$linkQuery = $db->query($itemLink);
$fetchItem = $itemQuery->fetchAll(PDO::FETCH_ASSOC);
$fetchLink = $linkQuery->fetchAll(PDO::FETCH_ASSOC);
$merged = array_merge($fetchItem,$fetchLink);
foreach($merged as $entry) {
foreach( $entry as $key => $value ) {
}
}
From the above code, how do I output only the items' datas?
Using the example above you could then do something like this to answer you question
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["FirstName"] . " " . $row["LastName"] . "<br>";
}
mysql_close($conn);
?>
I would use something like this, not two arrays for something that could be one query. I have shown three methods, using var_dump or print_r will show how each works.
$conn = mysql_connect($hostname, $username, $password);
if (!$conn) {
die('Could not connect to MySQL: ' . mysqli_connect_error());
}
$db_selected = mysql_select_db('sample', $conn);
if (!$db_selected) {
die("Can\t use db : ' . mysql_error()");
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
$result = mysql_query('Select * from names ');
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
print_r($row);
}
mysql_close($conn);

Categories