mysql_fetch_array($result) echo $rows in html - php

So I have these specific rows that I'm pulling if a code matches the database but I have no idea on how to echo this to my full html, is there anyway to make this $rows a $_POST or $_get to html?
thanks
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database,$connection)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "Hello: $name $test";
}
} else {
echo "error msg";
}
mysql_close($connection);
?>

You just need to update your while loop
Following code is to create your result Array, by that result array you can use the values in HTML too.
$resArr = array();
while($row = mysql_fetch_array($result)) {
$resArr[] = $row;
}
echo "<pre>";print_R($resArr);exit;

try
$query = "SELECT * FROM '$table' WHERE '$field' = '".$_GET["qcode"]."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_assoc($result))
{
$name1 = $row[$field];
$test1 = $row[$test];
echo "Hello:" .$name1. $test1;
}
}
else { echo "error msg"; }
Also use mysql_real_escape_string() to prevent sql injection or better to use mysqli or PDO

You have two alternatives :
i) Use a .php file and write the html part there. This way you run php code with simple, php tags and display stuff where you need.
example :
Create a file called test.php and put this code in it and run.
</head>
<body>
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database,$connection)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "<p>".$name." ".$test."</p>";
}
}
else { echo "error msg"; }
mysql_close($connection);
?>
</body>
</html>
This example puts the content in a paragraph in the html.
ii) echo the content from php by encoding it JSON and receive it using jquery from your html form. I'll not elaborate on this since it is not in the scope of the question.
And DO REMEMBER TO USE THE mysql_real_escape_string() to keep your code robust and prevent sql injection.

Related

android - php fetch mysql data by user id

This my PHP URL for fetching the data from MySQL. I need to make mysqli_fetch_array code saying if filled uid in the app-data table is the same with uid in users table fetch the data from all row in app-data to the uid like every user show his items from app-data table.
$host = "";
$user = "";
$pwd = "";
$db = "";
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT * FROM app_data ORDER By id";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
I think this is the correct answer:
<?php
$host = "";
$user = "";
$pwd = "";
$db = "";
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT * FROM app_data WHERE u_id=".$_POST['posted_uid']." ORDER By id";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
Little tip for the future:
Don't search exactly what you want, only search in parts.

extracting an array from a database in php

im currently trying to extract a table from my database (articles) and the table article and put it in an array but im not sure weather or not it wokred because i dont know how to print an array. i was following this link.
http://phpscriptarray.com/php-arrays-tutorials-tour/how-to-extract-mysql-database-data-into-php-array-variable.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// create connection
$conn = new mysqli($servername, $username, $password);
// check connection
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
// connect to DB
$db_selected = mysqli_select_db('article', $conn);
if (!$db_selected){
die("can't use article : " .mysqli_error());
}
// extract databases table to PHP array
$query = "SELECT * FROM `articles`";
$result = mysqli_query($query);
$number = mysql_numrows($result);
$article_array = array();
$x = 0
while($x < $number)
{
$row = mysqli_fetch_array($result);
$artic = $row['name'];
$amount = $row['quantity'];
$article_array[$artic] = $amount;
$x++;
}
echo count($article_array);
//echo "hello";
<?
even the echo hello wont work and im not sure if i was supposed to put a name and quantity in:
$artic = $row['name'];
$amount = $row['quantity'];
You are mixing object oriented with procedural style. Your query and loop should look like this:
$query = "SELECT * FROM `articles`";
$result = $conn->query($query);
$article_array = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$artic = $row['name'];
$amount = $row['quantity'];
$article_array[$artic] = $amount;
}
http://php.net/manual/en/mysqli.query.php
Also your PHP closing tag is faulty - should be ?> or omitted.

mysql_query how to display html for if condition

So I have this rustic and basic php that will check a value in my database and if its corrects it will pull out the rest of that row I guess but my problem is how to echo certaine html if the result is okay and how to echo some other html if else.
btw atm else is not working, in other words if you input a code that is not on my db it will not show anything
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "Hello: $name $test";
}
}
else {
echo "Im sorry you buddy, you are not a winner this time! $test";
}
mysql_close($connection);
?>
You can use mysql_num_rows(), it's the best way.
if( mysql_num_rows($result) > 0 ){
/* Anything you want here on success */
} else {
/* Anything you want here on failure */
}
if(mysql_num_rows($result) > 0) { echo "output"; } else { echo "error msg"; }
Use mysql_num_rows against the query.
if(mysql_num_rows($result)){ } else { }
Instead of echoing every html value you can simply enclose html in if statements
like:
<?php
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
?>
<b>Hello: <?php echo $name $test"; ?></b>
<?php
}
}
else {
?>
<b> Im sorry you buddy, you are not a winner this time! </b> <?php echo $test";
}
mysql_close($connection);
?>
First you have to correct syntax of database selection like this
mysql_select_db($db_database,$connection);
Insted of
mysql_select_db($db_database);
Check Manual

Multi URL paramaters with PHP and SQL

<?php
$username = "username";
$password = "password";
$hostname = "localhost";
$database = "database";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select database");
$id = 0;
if(isset($_GET['Day'])){ $id = (int)$_GET['Day']; }
if(!$id){
$query = "SELECT * FROM `TimeTable`";
} else {
$query = "SELECT * FROM `TimeTable` WHERE `Day`='".$id."'";
}
$result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
or die(mysql_error());
print json_encode($rows);
?>
This code worked previously, but has now stopped, and is producing Parse error: syntax error, unexpected T_LOGICAL_OR in /Directory/TimeTable.php on line 27
I am also looking to add more parameters, (eg: Where Day = $id and Year = $Year )
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
or die(mysql_error());
This is a syntax error, doesn't know what to do with that or die() statement. Change to this:
$result = mysql_query($query);
if (!$result) {
die('Error');
}
while(...) {
}
I have looked up the new mysql functions an have changed to mysqli.
<?php
$username = "username";
$password = "password";
$hostname = "localhost";
$database = "database";
$link = mysqli_connect($hostname, $username, $password, $database);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$id= 0;
if(isset($_GET['Day'])){ $id=(int)$_GET['Day']; }
$year = 0;
if(isset($_GET['Year'])){ $year=(int)$_GET['Year'];}
if(!$id){
$query = "SELECT * FROM TimeTable";
} else {
if (!year) {
$query = "Select * FROM TimeTable";
} else {
$query = "SELECT * FROM TimeTable WHERE Day=$id AND Year=$year";
}
}
$rows = array();
//Perform JSON encode
if($result = mysqli_query($link, $query)){
while($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
}
print json_encode($rows);
?>

mysql_query SELECT do not give the desired result

The following code always displays
rows = 0
eventhough the table contains Ravi in the field 'to'. Does anyone know what is wrong with this code?
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE to = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
echo $result["to"] + " " + $result["from"];
} else {
echo 'rows = 0';
}
} else {
echo 'empty for Ravi';
}
//} else {
//}
?>
to is a reserved word in MySQL, if you want to use it you must encase it in backticks:
.... WHERE `to` = ...
I have not look at your code but I recommend looking at
http://php.net/manual/en/intro.mysql.php
this before you continue to use mysql and not mysqli. It isn't that different but mysqli seems to have a wrapper over mysql and uses the "->" to instantiate new classes for a connection. If that makes any sense.
Try this:
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
echo $row["to"] + " " + $row["from"];
} else {
echo 'rows = 0';
}
} else {
echo "empty for $to";
}
//} else {
//}
?>
MYSQLI version + some adjustments:
<?PHP
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
$result = mysqli_query($link, $query);
if (mysql_num_rows($result)>0) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $row["to"]. "+". $row["from"];
}
}
ELSE {
echo 'rows = 0';
}
}
mysqli_close($link);
?>
I would like to credit #njk and #Wezy for their contribution with regard to the reserved word to in mysql. The WHILE loop is not necessary if the table events can only contain one "to" in this case "Ravi". I suspect that the number of events can be greater than one.
#Wezy has a point but let's do the troubleshooting:
As #JonathanRomer in his comment suggested, do:
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'") or die(mysql_error());
What does it say? Does it fail at all?
Or, just before mysql_query do:
die("SELECT *FROM `events` WHERE `to` = '$to'");
this will print faulty query being executed. Next, fire up mysql console or PHPMyAdmin and try executing this query manually.
Again, what does it say?
Actually, my main purpose was to encode this message and receive it on a mobile device by using JSON. This is the full code. For normal checking purpose, instead of using json_encode(*), the values can be displayed individually. This is the solution I got and it is working perfectly for receiving the data in an android app on which I am working.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$response = array();
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = mysqli_connect_error();
echo json_encode($response);
}
if(isset($_POST['to'])) {
$to = $_POST['to'];
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
if($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
$i = 0;
if($stmt->num_rows > 0) {
$stmt->bind_result($rowto, $rowfrom, $rowevent);
$response["events"] = array();
while($stmt->fetch()) {
$events = array();
$events["to"] = $rowto;
$events["from"] = $rowfrom;
$events["event"] = $rowevent;
array_push($response["events"], $events);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No events found";
echo json_encode($response);
}
$stmt->close();
}
} else {
$response["success"] = 0;
$response["message"] = "Required fields are missing";
echo json_encode($response);
}
$mysqli->close();
?>

Categories