I am building a site, and essentially what this PHP algorithm will do is look at a product (row in MySQL database) one at a time, and do a process accordingly.
I put a lot of research into this but couldn't find anything, any help would be greatly appreciated!
My Code (currently returning nothing for echo variables):
<?php
include_once 'dbconnect.php';
$query = "SELECT * FROM track";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$pro_code = mysql_result(mysql_fetch_array(mysql_query('SELECT product_code FROM track')));
$currency = mysql_fetch_array(mysql_query('SELECT currency FROM track'));
$cc = mysql_fetch_array(mysql_query('SELECT cctld FROM track'));
$initial_price = mysql_fetch_array(mysql_query('SELECT initial_price FROM track'));
$url = 'test';
}
echo $pro_code;
echo $currency;
echo $initial_price;
?>
First of all, try the advice about PDO and stuff from Jay Blanchard some day.
Secondly I've tried to answer your question anyway and I've tried to interpret your complete intention. I put comments in the code:
<?php
include_once 'dbconnect.php';
$query = "SELECT * FROM track";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
//You need to read the row variable as an array
$pro_code = $row['product_code'];
$currency = $row['currency'];
$cc = $row['cctld'];
$initial_price = $row['initial_price'];
//$url is not used.. I asume a test to get the external source ;-)
$url = 'test';
if ($url == $cc) {
//if you want to print every row, you must echo inside the while loop
echo $pro_code;
echo $currency;
echo $initial_price;
} elseif ($url == 'test') {
//do something else here
} else {
//do something for all the other cases here
}//end if
}//end while
?>
Why do you query the same table multiple times, your code should be written like this:
include_once 'dbconnect.php';
$query = "SELECT product_code, currency, cctld, initial_price FROM track";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo $row['product_code'];
echo $row['currency'];
echo $row['cctld'];
echo $row['initial_price'];
}
and please upgrade to mysqli or PDO
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.
My php While loop run the query, but the results must be print inside html. In this moment I unknow the way to make this:
My php while loop
<?php
include "connect.php";
$username=$_SESSION['Username'];
$result = mysqli_query($dbconn,"
SELECT *
FROM books
WHERE username = '$Username'
");
while($rows = mysqli_fetch_array($result));
?>
After this code there is a Html code where I want print the variables:
Edit
In this moment the variable is empty
How to fix this?
[Resolved] Update
I have resolve my problem. This is the correct php script. Work fine:
<?php
include "connect.php";
$username=$_SESSION['Username'];
$result = mysqli_query($dbconn,"
SELECT *
FROM books
WHERE username = '$Username'
");
global $book_id, $book_name
while($row = mysqli_fetch_array($result)) {
$book_id = row['book_id'];
$book_name = row['book_name'];
?>
Outside while loop. Print variable inside Html:
<?php echo $row['book_id']; ?> <br>
<?php echo $row['book_name']; ?>
Close while loop and connection:
<?php
}
mysqli_close($dbconn);
?>
with prepared statements :
<?php
session_start();
$username = $_SESSION['Username'];
error_reporting(E_ALL);
ini_set('display_errors', 1);
include"config.inc.php";
/* connect to DB */
$mysqli = mysqli_connect("$host", "$user", "$mdp", "$db");
if (mysqli_connect_errno()) { echo "Error connecting : " . mysqli_connect_error($mysqli); }
$query = " SELECT * FROM books WHERE username=? ";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $username);
$results = $stmt->execute();
$stmt->bind_result($book_id, $book_name);
$stmt->store_result();
if ($stmt->num_rows > 0) {
while($stmt->fetch()){
?>
<p><?php echo"$book_name"; ?> > Edit</p>
<?php
}
}
else
{ echo"[ no data ]"; }
?>
(Rewriting)
The real issue is:
while ($rows = ...) ;
This loops until $rows is NULL. So there is nothing to display afterwards.
Since you are fetching the entire array in a single function call, there is no need for the loop!
$rows = ...;
But then you need to reference the first(?) row to get the desired data:
$row = $rows[0];
So, another approach is to just fetch one row, then close the fetch process.
In your html you have to do this
Edit
As there might be multiple books for each user, you have to print the link inside the while loop, or store it in a string:
<?php
include "connect.php";
$username = $_SESSION['Username'];
$result = mysqli_query($dbconn,"
SELECT * FROM books
WHERE username = '$Username'
");
$links = ""; // all links are stored in this string
while($rows = mysqli_fetch_array($result)) {
// I assume that the columns are called `id` and `name`
$links .= 'Edit '. $rows["name"] .'';
}
?>
In the html code simply write
<?php echo $links ?>
Note that you should use prepared statements instead. You should also take a look at the object oriented way to use mysqli using the mysqli class.
I am kinda new to SQL and I am having a problem. I am following the tutorial from Here to try to get data from my database into my android app.
I have it working, but it only gets one line. I know it should be possible to iterate through the database and echo out every line that matches the ID to JSON, but I do not know how. How would I do this?
My current code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM LATLON WHERE DeviceID='".$id."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"INDEX"=>$res['INDEX'],
"DeviceID"=>$res['DeviceID'],
"LAT"=>$res['LAT'],
"LON"=>$res['LON']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
?>
EDIT
I edited my code to this, but I am getting nothing. Still not quite understanding what is happening. Thanks for all the help!
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM LATLON WHERE DeviceID='".$id."'";
$r = mysqli_query($con,$sql);
while($row = $result->mysqli_fetch_array($r, MYSQLI_ASSOC)){
$array[] = $row;
}
echo json_encode($array);
mysqli_close($con);
}
?>
You can iterate through mysqli_fetch_array();
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$array[] = $row;
}
echo json_encode($array);
When you use the OO interface, the method names don't begin with mysqli_, that's only used for procedural calls. You also have no variable named $result, the result is in $r.
So it should be:
while ($row = $r->fetch_array(MYSQLI_ASSOC)) {
or:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
I'm trying to fetch couple of single data in my server database but this is throwing some errors. The incoming data is correct. The search function just don't get completed.
Here's the code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
define('HOST','xxxxxxxxxxx');
define('USER','xxxxxxxxxxxx');
define('PASS','xxxxxxxxx');
define('DB','xxxxxxxxxx');
$con = mysqli_connect(HOST,USER,PASS,DB);
$post_id = $_POST['id'];
$buyer_mobile = $_POST['mobile'];
$buyer_name = $_POST['name'];
$sql = "select mobile from flatowner where id='$post_id'";
$res = mysqli_query($con,$sql);
$owner_mobile = $row['mobile'];
$sql = "select name from user where mobile='$owner_mobile'";
$r = mysqli_query($con,$sql);
$owner_name = $row['name'];
$sql = "INSERT INTO flat_booking (post_id,owner_mobile,owner_name,buyer_mobile,buyer_name) VALUES ('$post_id','$owner_mobile','$owner_name','$buyer_mobile','$buyer_name')";
if(mysqli_query($con,$sql)){
echo "Success";
}
else{
echo "error";
}
mysqli_close($con);
}else{
echo 'error1';
}
What am I doing wrong here? Maybe this:
$owner_mobile = $row['mobile'];
Thanks in advance!
create table flatower and add mobile column
$post_id = 1;
$sql = "select mobile from flatowner where id='$post_id'";
$res = mysql_query($con,$sql);
$row = mysql_fetch_array($res);
$owner_mobile = $row[0]['mobile'];
Your problem is this line:
$owner_mobile = $row['mobile'];
You have not created the $row variable. For this you would need to do something such as:
Do this first:
<?php
$row = array();
while ($result = mysqli_fetch_assoc($res))
{
$row[] = $result;
}
?>
This allows you to do this:
<?php
foreach ($row as $r)
{
var_dump($r); print "<br />"; // One row from the DB per var dump
}
?>
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>";