While loop is printing two times output - php

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()

Related

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);

Storing the result of an SQL call in a php variable

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'];

Show muliple records from mysql

I have a php webpage that I want it to show all forum threads at once. He is the current db code i have, it only shows on thread.
mysql_connect("localhost", "", "") or die("could not connect to mysql");
mysql_select_db("") or die("could not connect to db");
$result = mysql_query("SELECT * FROM reference")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo "<strong>ref_thread_id:</strong> ".$row['ref_thread_id'].'<br />';
echo "<strong>ref_thread_prefix:</strong> ".$row['ref_thread_prefix'].'<br />';
echo "<strong>ref_thread_topic:</strong> ".$row['ref_thread_topic'].'<br />';
echo "<strong>ref_thread_content:</strong> ".$row['ref_thread_content'].'<br />';
How do I get it to spit out every record in this table?
Thanks.
You'd need to use a while loop. the fetch functions only get one row at a time.
while($row = mysql_fetch_array($result)) {
echo ...
}
You're only grabbing the first record, loop through each one:
while ( $row = mysql_fetch_array( $result )) {
echo "<strong>ref_thread_id:</strong> ".$row['ref_thread_id'].'<br />';
echo "<strong>ref_thread_prefix:</strong> ".$row['ref_thread_prefix'].'<br />';
echo "<strong>ref_thread_topic:</strong> ".$row['ref_thread_topic'].'<br />';
echo "<strong>ref_thread_content:</strong> ".$row['ref_thread_content'].'<br />';
}
Use a loop:
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
(Example part taken from http://php.net/manual/en/function.mysql-fetch-array.php)

Fetch information from mysql db using php

Updated script with proper field names. Why isnt this working?
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bookorama", $con);
$sql="SELECT * FROM customers";
$result = mysql_query($sql); // You actually have to execute the $sql with mysql_query();
echo "<table>"; //start the table
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results
{
//echo each row of the table
echo "<tr>
<td>$row['customerID']</td>
<td>$row['name']</td>
<td>$row['Aaddress']</td>
<td>$row['city']</td>
</tr>";
}
echo '</table>'; //close out the table
?>
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bookorama", $con);
$sql="SELECT * FROM customers";
$result = mysql_query($sql); // You actually have to execute the $sql with mysql_query();
echo "<table>"; //start the table
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results
{
//echo each row of the table
echo "<tr>";
echo "<td>$row['CustomerID']</td>";
echo "<td>$row['address']</td>";
echo "<td>$row['city']</td>";
echo "</tr>";
}
echo '</table>'; //close out the table
?>
You can mysql_fetch_array or mysql_fetch_assoc to retriever the rows from you query.
For example using mysql_fetch_array:
$result = mysql_query($sql);
echo "<table><tbody>";
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<tr><td>".$row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
echo "</tbody></table>"
You need to run the query and loop through the results.
You are better off learning from day one about PDO.
And also don't interpolate directly from any user submitted variables (that includes $_POST).
Pretty sure you need to do this when embedding anything more complex than scalars inside double quotes
echo "<tr>
<td>{$row['CustomerID']}</td>
<td>{$row['address']}</td>
<td>{$row['city']}</td>
</tr>";
So whenever you have a more complex var name than "test $var" in quotes, wrap with {} - and even then, it's good practice to wrap scalars too like "test {$var}"

How can I get a result from mysql_fetch_row (or mysql_fetch_array)

$sqlQuery = "SELECT * FROM allowedUsers WHERE UserID = '" . $kUserID . "'";
$result=mysql_query($sqlQuery, $db);
if(!result)
{
echo "Error running query <br>" . mysql_error();
exit;
}
while($row = mysql_fetch_array($result))
{
echo $row[2];
}
I run the SQLQuery in phpMyAdmin and I am getting a valid result (1 row)
the table (allowedUsers) has 6 fields
I can't get anything out of the DB.
Any help is appreciated.
if(!result) should be if(!$result)
According to PHP.net's documentation, you don't need to pass $db to mysql_query(). Take a look at the example code:
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>
It may be helpful to see your connection code, ensure you've selected a database, etc.

Categories