I really hope I'm not just being stupid. I'm trying to retrieve two values from a existing database, based on a user's ID. I've been trying a couple of different things, so I've got some commented code in case I was close!
I'm using a select statement to get the values, and then trying to pass them to PHP variables. I'm getting the values from the DB, just not setting them as PHP variables.
<?php
//declare database variables
header('Content-type: text/html; charset=utf-8');
$username = "ishuttle";
$password = "";
$hostname = "localhost";
$dbname = "ishuttle_taxi-location";
$conn = mysql_connect($hostname, $username, $password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
//search database for driver location
mysql_select_db('ishuttle_taxi-location');
$sql = "SELECT _id, Latitude, Longitude
FROM driver_location
WHERE _id = 2";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo "Lat :{$row['Latitude']} <br> ".
"Long: {$row['Longitude']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
$Lat = $retval[1];
$Long = $retval[2];
echo "$Lat";
?>
Cheers in advance :)
Assign the variables inside the while loop. Change
while($row = mysql_fetch_assoc($retval))
{
echo "Lat :{$row['Latitude']} <br> ".
"Long: {$row['Longitude']} <br> ".
"--------------------------------<br>";
}
to
while($row = mysql_fetch_assoc($retval))
{
$Lat = $row['Latitude'];
$Long = $row['Longitude'];
echo "Lat :{$row['Latitude']} <br> ".
"Long: {$row['Longitude']} <br> ".
"--------------------------------<br>";
}
This is wrong:
$Lat = $retval[1];
^^^^^^
$retval is your result handle from the mysql query. It's NOT an array of results.
Related
I am trying to use a FOREACH loop to query a database based on each value in the $userid array below. I am also looping through the $grade array as I need the corresponding value for the sql query to then put into a HTML table.
//Decode JSON file to an Object
$json_d = json_decode(file_get_contents("results.json"));
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<table><tr><th>First Name </th><th>Last Name </th><th>Grade </th></tr>";
foreach($userid as $id) {
foreach($grade as $grd) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["firstname"]. "</td><td>" . $row["lastname"]. "</td><td> " . $grd . "</td></tr>";
}
} else {
echo "ERROR!";
}
}
}
echo "</table>";
mysqli_close($conn);
I have checked the $grade and $userid array and they do contain the correct values however running the PHP file I only get the first record outputted in the table. E.G.
FirstName LastName Grade
Student 1 85
Whereas I need the other 2 records that are supposed to appear.
I am trying to get my PHP script to print all rows i have in my database in a neat order. Currently Im not getting anything. My table has 4 columns, Name, Address, Long and Lat, and 2 rows with data. The table is called Locations. I am using the following code but im not getting to to work:
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
Here is a simple example using pdo instead of mysqli
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection
$stmt = $pdo->prepare("SELECT Name, Address, Long, Lat FROM Locations");
//you should never use *, just call each field name you are going to use
$stmt->execute(); // run the statement
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array
print_r($arr); // print all array items, unformatted
and you can echo out the data and format it yourself using a for loop like so
for($i=0; $i<sizeof($arr); $i++) { // this will loop through each row in the database. i prefer this method over while loops as testing has shown this is much faster for large scale tables
echo 'Name: ' . $arr[$i]['Name'] . '<br />'; // $arr is the array name, $i is the number of the array item, or iterator, ['Name'] is the field name
echo 'Address: ' . $arr[$i]['Address'] . '<br>';
echo 'Long: ' . $arr[$i]['Long'] . '<br>';
echo 'Lat: ' . $arr[$i]['Lat'] . '<br>';
}
If the names are correct, this would echo out your row ID and row CITY. Just change the names to your field names. If you want further assistance, feel free to ask.
However, if you want to stick with mysqli, give the following code a wirl.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$mysqli = mysqli_connect($dbHOST, $dbUSER, $dbPASS, $dbNAME);
$query = "SELECT Name, Address, Long, Lat FROM Locations";
$result = mysqli_query($mysqli, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo 'Name: ' . $row['Name'] . '<br />';
echo 'Address: ' . $row['Address'] . '<br>';
echo 'Long: ' . $row['Long'] . '<br>';
echo 'Lat: ' . $row['Lat'] . '<br>';
}
}
change fieldname to the field you want to display
EDIT: Paste the following code. It will echo out the number of rows. This will tell you if the query statement is correct.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS);
$stmt = $pdo->query("SELECT Name, Address, Long, Lat FROM Locations");
echo $stmt->rowCount();
Fetch query result as associative array and use for each to print all results
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
while($rows = mysqli_fetch_assoc($result)) {
foreach($rows as $key => $val)
{
echo $val;
}
}
}
mysqli_close($con);
?>
I'm not wholly proficient with PHP but I'm having a few problems echoing a gathered value from a MySQL query function.
I believe I know where the problem lies but I'm not competent enough to fix it, if you could please help it would be appreciated.
PHP Function (Works perfectly).
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT Name, Role, Salary FROM `users-table`';
mysql_select_db('user_records');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "--------------------------------<br>",
"Name: {$row['Name']} <br> ".
"Role: {$row['Role']} <br> ".
"Salary : {$row['Salary']} <br> ".
"--------------------------------<br>";
}
mysql_close($conn);
?>
This displays the data perfectly! However I'm now trying to include this in a nicely formatted HTML table. (Which is why I'm closing the php tag above).
I'm then trying to use a table like this:
<table >
<tr>
<td>
<?php echo $row['Name'] ?>
</td>
....
It outputs nothing, - I think this problem is caused because I close the first function and then try to reference $row and it doesn't know what to do...?
I think I need to tap in to while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
How can I re-factor this so that I can echo content from the above function to my table?
You didn't write the code you tried, but here is something functional:
$link = mysqli_connect("myhost", "myuser", "mypassw", "mybd");
echo "<table>";
while ($row = mysqli_fetch_array($link, $retval, MYSQL_ASSOC)) {
echo "
<tr>
<td>{$row['Name']}</td>
<td>{$row['Role']}</td>
<td>{$row['Salary']}</td>
</tr>
";
}
echo "</table>";
PS: Since MySQL is deprecated, I replaced your code with MySQLi, and I suggest you do the same :)
As #zessx said, yous should use MySQLi or PDO.
anyway to answer to your question, you have to change the loop in your php code from
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "--------------------------------<br>",
"Name: {$row['Name']} <br> ".
"Role: {$row['Role']} <br> ".
"Salary : {$row['Salary']} <br> ".
"--------------------------------<br>";
}
to
echo '<table>';
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo " <tr>" .
" <td>Name: {$row['Name']}</td>".
" <td>Role: {$row['Role']}</td>".
" <td>Salary : {$row['Salary']}</td>".
" </tr>";
}
echo '</table>';
I have write some php code to retrieve some records from a mysql database in the form of table. the table have three columns where first two were filled up from the database and the third is a drop down list for each row. Now I want to select the drop down list from the populated rows and store the information of each rows in a new database.
Please view the codes and reply for your suggestions.
<html>
<?
// data from the "recordentry.php";
$date = $_POST['date'];
$course = $_POST['course'];
$period = $_POST['period'];
$batch = $_POST['batch'];
$subject = $_POST['subject'];
$faculty = $_POST['faculty'];
?>
<p> Current Date&Time:<? echo $date ?></p>
<form enctype="multipart/form-data" name="f1" method="POST" ACTION="<?=$self ?>"">
<?
$db = "contact";
//mysql_connect(localhost,$_POST['username'],$_POST['pass']);
$link = mysql_connect("localhost", "root", "");
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db($db, $link) or die("Couldn't open $db: " . mysql_error());
$result = mysql_query("SELECT name,uic FROM student where batch='$batch' AND course='$course' order by name") or die("SELECT ERROR: " . mysql_error());
$num_rows = mysql_num_rows($result);
echo "<table border='1' align='center'><tr><th>Name</th><th>Unique Identification Code</th>
<th>Attendance</th></tr>";
while ($row = mysql_fetch_array($result))
{
//Display the results in different cells
echo "<tr><td align=center>" . $row['name'] . "</td><td align=center>" . $row['uic'] . "</td><td align=center><select name='attendance' style='background-color:#FFC'>
<option>Present
<option>Absent
</select></td></tr>";
$data[] = array(
'name' => $row['name'],
'uic' => $row['uic'],
'attendance' => $row['attendance']
);
}
echo "<tr><td><input type='submit' value='Submit' name='submit_button' />";
echo "</table>";
foreach ($data as $value)
{
$name = mysql_result($value['name']);
$uic = mysql_result($value['uic']);
$a_status = mysql_result($value['attendance']);
$db = "contact";
$link = mysql_connect("localhost", "root", "");
//$link = mysql_connect("localhost",$_POST['username'],$_POST['password']);
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db($db, $link) or die("Select Error: " . mysql_error());
$result = mysql_query("INSERT INTO attendance(date, course, period, batch, subject, faculty,name, uic, attendance) VALUES ('$date', '$course', '$period', '$batch', '$subject', '$faculty', '$name', '$uic', '$a_status')") or die("Insert Error: " . mysql_error());
mysql_close($link);
}
?>
</form>
</html>
the above code can populate the table off all the retrieved data from the database. but after submit it can not store the last three fields $name, $uic and $attendance. so, please help me.
Try this:
$name = mysql_result($result, $value['name']);
$uic = mysql_result($result, $value['uic']);
$a_status = mysql_result($result, $value['attendance']);
This will get the values once - but you reuse $result in that query (when you insert) so it will get overwritten. Change either the first call or the second.
I am working in android and php.
I want to return a json object to android program from php program.
If these is a entry in a database then it is working properly. But when there is no record in database then it goes wrong.
I would welcome suggestions
I want to make json object like this ([{"id":"5"}])
This is my php program:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
//what should i right here to make jsonobject like this:- ([{"id":"5"}])
echo myjsono;
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
?>
How about something like this: (replace with your own variables)
if (empty($row)){
$arr = array('success' => 'false');
} else {
$arr = array('success' => 'true');
}
echo json_encode($arr);
If you want your android app to receive an object with a special id in the case of a not found condition I would return this:
{"id":"0"}
Then in your android app check if the id == 0 and that will tell you no records were found.
This is very correct solution for my question:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
// {"messages":{"message":[{"id": "17","user": "Ryan Smith","text": "This is an example of JSON","time": "04:41"}]};}
**echo '('.'['.json_encode(array('id' => 0)).']'.')';** //**note this**
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
//mysql_close($con);
//echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>