I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>
Related
I wrote simple code to fetch data from MySQL using PHP.
This is the code:
<?php
$mangkal = $_POST['mangkal'];
$lat = $_POST['lat'];
$long = $_POST['long'];
$mysqli = new mysqli("localhost", "root", "", "mad");
$query = "SELECT * FROM kendaraan WHERE mangkal LIKE '%$mangkal%' ORDER BY id DESC";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_BOTH);
{
echo "<p>";
echo "$row[id_kendaraan]";
echo "<p>";
echo "$row[mangkal]";
}
?>
The script is working, if the data is returned by the db call, I can see the results displayed. But, if the query result has no data, the script just displays blank. I want to show a message that says - 'Data not found'. How can I do that?
I have more than one record for a query but the script displays just one data. Please help me to show all records.
Use a while loop like following:
if($result->num_rows > 0)
{
while($row = $result->fetch_array(MYSQLI_BOTH))
{
echo "<p>".$row[id_kendaraan]."</p><br><p>".$row[mangkal]."</p>";
}
} else {
echo "No Record Found.";
}
You need to run a loop to iterate through each result. Something similar to this -
<?php
$mangkal = $_POST['mangkal'];
$lat = $_POST['lat'];
$long = $_POST['long'];
$mysqli = new mysqli("localhost", "root", "", "mad");
$query = "SELECT * FROM kendaraan WHERE mangkal LIKE '%$mangkal%' ORDER BY id DESC";
$result = $mysqli->query($query);
while($row = $result->fetch_array(MYSQLI_BOTH)) {
echo "<p>";
echo "$row[id_kendaraan]";
echo "</p><p>";
echo "$row[mangkal]";
echo "</p>";
}
?>
In the code above, a while loop is used to iterate through results one by one. Each time $row will be updated with new data and will be printed.
i'm a newbie to php still.
I'm using phpmyadmin as my database. I have a table called 'lessonno' and a column named 'lesson' in it. I tried using this code to retrieve out the number inside 'lesson'. But it's not printing out anything. Can someone help?
<?php
$server = 'localhost';
$username = '';
$password = '';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$sql = "SELECT 'lesson' FROM 'lessonno'";
$lesson = $_POST['lesson'];
$result = mysql_query($sql);
?>
<?php
for($i = 1; $i <= $lesson; $i++) {
echo "<div>
<span>Lesson ".$i."</span>
</div>
<br>";
}
?>
You can use something like this:
$sql = "SELECT lesson FROM lessonno";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['lesson'];
}
If you would like to only print out a specific lesson with an certan ID, you can use something along the lines:
$id = $_GET['lessonid']; // If you would have something like index.php?lessonid=36 and you'd like it to only fetch the data for the lesson with the id of 36.
$sql = "SELECT lesson FROM lessonno WHERE id='$id'";
(by looking at the $_POST['lesson'] part, I suppose that's something you might be trying to do as it's in the for loop as well)
Also, I suggest you use mysqli.
And, this:
echo "<div>
<span>Lesson ".$i."</span>
</div>
<br>";
Will just echo the $i as both lesson= and the span with Lesson, which won't grab any information from the actual database but just go with the current number it's at, from the for loop you have.
i have made some changes in your code try this
<?php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'project';
$conn = mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database, $conn) or die(mysql_error());
$sql = "SELECT `lesson` FROM `lessonno`";
$lesson = $_POST['lesson'];
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$lesson_no = $row['lesson'];
echo "<div>
<span>Lesson ".$lesson_no."</span>
</div>
<br>";
}
?>
Note : mysql_* is deprecated. use mysqli_* OR PDO
For getting Values from DB you need to use something like this
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
For further reference please visit http://in2.php.net/manual/en/function.mysql-fetch-assoc.php
For counting the number of data in your database, just insert this code
$sql = "SELECT 'lesson' FROM 'lessonno'";
$lesson = $_POST['lesson'];
$result = mysql_query($sql);
$count=mysql_num_rows($result);//this will count the number of rows in your table.
echo "<div>
<span>Lesson ".$count."</span>
</div>
<br>";
So I've been working on a little automatic payment system, and I'm almost done! My customers will get their account upgraded automatically after payment, but I have a slight problem.
I'm currently manually adding their username to an array which changes their username style to distinguish their rank.
I would like to know how to make it retrieve and successful go into an array which will then be called and show their new username.
Here is my code for retrieving usernames and then putting into an array:
$db = new mysqli("localhost", "changed", "changed", "changed")or die(mysqli_error());
$listmembers = $db->query("SELECT * FROM members")or die(mysqli_error());
$names = array();
while($listnames = $listmembers->fetch_assoc()) {
$names[] = "'" . $listnames['username'];
}
$newname = explode("\", ", $names);
Okay and this is what my array code looks like
$members = array($newname);
And this is the code changing their rank:
if(in_array(strtolower($rows['received']), $members)) {
$user = "" . ucfirst($rows['received']) . "";
}
If anyone cold help me, i'd appreciate it.
Turn warnings on to see a few of your mistakes..
$db = new mysqli("localhost", "changed", "changed", "changed")or die(mysqli_error());
$listmembers = $db->query("SELECT * FROM members")or die(mysqli_error());
$names = array();
while($listnames = $listmembers->fetch_assoc()) {
$names[] = $listnames['username'];
}
and later something like this..
if(in_array(strtolower($rows['received']), $names)) {
$user = "<font color=\"lime\"><b>" . ucfirst($rows['received']) . "</b></font>";
}
why you don't fetch array directly from database?
$db = new mysqli("localhost", "changed", "changed", "changed")or die(mysqli_error());
$listmembers = $db->query("SELECT username FROM members")or die(mysqli_error());
$names = $listmembers->fetch_all();
and then:
foreach ( $names as $username ) {
if ( strtolower($rows['received']) == $username[0] ) {
$user = ucfirst($rows['received']);
break;
}
}
I edit my code working good but still one problem ... the data that selected from my database and displayed in my suggestion input ( only one row and last ID ) !!! How can I do it to display all data rows from my database ????
<?php
$q = strtolower($_GET["q"]);
if (!$q) return;
$host = "localhost";
$user = "root";
$password = "";
$database = "private_message_system";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query)){
$items = array($row["user_name"] => $row["user_email"]);
}
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key,
"to" => $value
));
}
}
echo json_encode($result);
?>
As I know mysql doesn't have a array type like postgres so you have to fetch it one by one:
// here is where you get your to connection to the database
$conn = mysql_connect("your IP", "username", "password");
mysql_select_db("mydb", $conn);
// here you have to do the select to retrieve data from the table.
$query = "SELECT `name`, `to` from mytable";
// now you got all the records but you still need to iterate over this result
$result = mysql_query($query, $conn);
$array = array();
// retrieve a record and append it to the array
while($record = mysql_fetch_assoc($result)):
$array[] = $record;
endwhile;
// please close the door....
mysql_close($conn);
echo json_encode($array);
See below for a basic implementation of connecting to MySQL and searching for your $q, I've left a few comments for you to make it clearer what's going on!
<?php
// Get the query term from the url
$q = strtolower($_GET["q"]);
// Do nothing if it's empty or not set
if (empty($q)) return;
// Result array which we are going to get from MySQL
$result= array();
// Make a SQL Connection
mysql_connect("localhost", "admin", "password") or die(mysql_error());
// Try to connect to your DATABASE (change the name) or throw an error
mysql_select_db("DATABASE") or die(mysql_error());
// Get data from the "email" table
// Where the name field is LIKE the search term
$result = mysql_query("SELECT * FROM email WHERE name LIKE '%".mysqli_real_escape_string($q)."%'")
or die(mysql_error()); //throw an error if something went wrong
//Read all the results ($row) in a loop and put them in the result array
while($row = mysql_fetch_array( $result )) {
$result[] = array('name' => $row['name'], 'to' => $row['to']);
}
// Output the array as JSON
echo json_encode($result);
?>
For the more PHP experienced I am aware you can get an array from MySQL but have left it like this to make it clearer.
Enable error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);
I have a function that I can get all the correct values for with an echo, but when I cannot figure out how to get the whole array returned. Could someone help me figure out to get the all of the child users?
$useridarray[] = $userid;
getchildren($useridarray, $useridarray);
function getchildren($array, $totalarray)
{
foreach($array as $arr)
{
$db_name = "dbname";
$connection = #mysql_connect("localhost", "username", "password") or die(mysql_error());
$db = #mysql_select_db($db_name, $connection) or die(mysql_error());
$sql = "
select *
from users
where creator = '$arr'
";
$result = #mysql_query($sql, $connection) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$newchildren[] = $row['id'];
$totalarray[] = $row['id'];
//echo $row['id'] . ' ';
}
mysql_close();
getchildren($newchildren, $totalarray);
}
}
You need to pass by referenceĀDocs:
function getchildren($array, &$totalarray)
^
Usage:
$useridarray[] = $userid;
getchildren($useridarray, $useridarray);
var_dump($useridarray); # your result
You need add return before
mysql_close();
return getchildren($newchildren, $totalarray);
I am not familiar with PHP syntax but you likely want to implement a "Stopping Criteria" to return you results. So in your instance it would seem like you would want something where getChildren returns the localResults + recursive getChildren results that are totaled incrementally as you go through your foreach loop.