MYSQL Fetching rows into page - php

I am fetching data from mysql to a page, i am not sure if the way im doing it is appropiate. I am having trouble with fetching values into sections of the page.
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "xxx") or die (mysql_error ());
// Select database
mysql_select_db("xxx") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM news";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['editor_name'] . " " . $row['news_desc'];
echo "<br />";
}
// Close the database connection
mysql_close();
?>
</div> <!-- content #end -->
the database;
the above yields;
I want to do the following;
BY: Fadi
echo 'BY' $row['editor_name'] . " " . $row['news_desc'];
echo "<br />";
but it isn't working :( any tips

You are missing a concat operator after 'BY'. Should be
echo 'BY' . $row['editor_name'] . " " . $row['news_desc'];
echo "<br />";
OR tidier:
echo "BY {$row['editor_name']} {$row['news_desc']}<br/>";

If you want to return associative array you can try using this line:
...
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
...

You forgot one dot after 'BY'
echo 'BY' . $row['editor_name'] . ' ' . $row['news_desc'] . '<br />';

Related

Creating a PHP API (Convert data from mySQL to JSON);

So my 1st target is to convert expecting data from mySQL as JSON before use XML.
Things i trying to solve- Connect two tables from database for specific user and display it on screen.
Everything is in one PHP file:
<?php
include 'db.php';
session_start();
ob_start();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users
INNER JOIN user_quiz ON users.user_uid = user_quiz.user_uid
WHERE users.user_uid = '".$_SESSION['u_uid'] ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
// for check if record exist
echo "<br> id: ". $row["id"]. " - Name: ". $row["user_first"]. " " . $row["user_last"] . " id:" . $row["user_uid"] . " Selected qustion " . $row["q_topic"] . " ". $row["q_id"] . "<br>";
}
} else {
echo "0 results";
}
$myJSON = json_encode($outp);
echo $myJSON;
?>
So now where is a issue.. When i do SQL like that:
SQL:
$sql = "SELECT * FROM users";
PHP is convert data as JSON data... but when i trying to do that for specific user i have empty []... That's why i use echo to see if i have output or i have error but... i have displays value... Had no idea what's going on... need advice.

errorTable 'college.college' doesn't exist : query error

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include 'conn.php';
// Attempt select query execution
$db_select = mysqli_select_db($conn,'college');
if (!$db_select) {
die("Database selection failed:: " . mysql_error($conn));
}else{
} //You don't need a ; like you do in SQL
$result = mysqli_query($conn,"SELECT * FROM college") or die("error".mysqli_error($conn));
echo "<table>"; // start a table tag in the HTML
$result = array();
while($row = mysqli_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['city'] . "</td><td>" . $row['clients'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysqli_close($conn);
?>
I am getting error in query statemenet that table college does exist. I have created table college in phpmyadmin and populated it with fake values, but still I am getting query error. The error is in line 14.

Search Using PHP displays all Database Data

I am trying to search some data from a database. The search works fine, however if I click on search without entering anything into the form, it displays all the data on the database. Anyway I can fix this?
This is my php code.
$link=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_selected = mysqli_select_db($link,"AnimalTracker1");
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysqli_error($link));
}
$searchKeyword = $_POST['find']; // Sanitize this value first !!
$sql=mysqli_query($link, "Select * FROM Locations WHERE `Animal_Type` LIKE '%$searchKeyword%' ");
if ($sql == FALSE)
{
die($sql." Error on query: ".mysqli_error($link));
}
while($result = mysqli_fetch_array($sql))
{
echo $result ['Animal_Type'];
echo "<br>";
echo $result ['Latitude'];
echo "<br> ";
echo $result ['Longitude'];
echo " <br>";
echo $result ['Seen'];
echo " <br> ";
echo $result ['Time'];
echo "<br> ";
echo "<br> ";
}
//}
?>
Just make sure $searchKeyword has a (valid) value
$link=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_selected = mysqli_select_db($link,"AnimalTracker1");
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysqli_error($link));
}
// checks to see if $_POST['find'] is actually set.
if ( array_key_exists('find',$_POST) )
{
$searchKeyword = $_POST['find']; // Sanitize this value first !!
// sanitize $searchKeyword here
}
// checks to see if $searchKeyword has no value, or just contains empty space
if ( empty(trim($searchKeyword)) )
{
echo "You must enter a search term";
}
else
{
$sql=mysqli_query($link, "Select * FROM Locations WHERE `Animal_Type` LIKE '%$searchKeyword%' ");
if ($sql == FALSE)
{
die($sql." Error on query: ".mysqli_error($link));
}
while($result = mysqli_fetch_array($sql))
{
echo $result ['Animal_Type'];
echo "<br>";
echo $result ['Latitude'];
echo "<br> ";
echo $result ['Longitude'];
echo " <br>";
echo $result ['Seen'];
echo " <br> ";
echo $result ['Time'];
echo "<br> ";
echo "<br> ";
}
}
?>
Try removing the "%" from either the back or the front of the $searchKeyword in the query and I guess it should do the work.
"%" is used when match all or none. So if you send an empty string it will return the whole database.

Printing result of mySQL query with INNER JOIN

I have a working SQL statement that returned correct results when I checked it on MAMP.
SELECT `questions`.`questionID` AS question, `questions`.`questionText`,
`questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,
`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`
But I can't figure out how to print the output with php. Please help. This is the code:
<html>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$con=mysqli_connect("localhost","root","root","Theory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questions'.'questionID'] . "}"; //this is not the full print
echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking
echo "}";
}
mysqli_close($con);
?>
</body>
</head>
I get:"{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}" echoed.
You're executing a query again inside your if condition... But the $sql query is empty because the variable is not defined!
replace if (!mysqli_query($con,$sql)) with if (!$result) since you have already executed the query in the rows above.
EDIT to answer the question's comments:
when you're fetching the resulting array, you don't need to specify the table alias but just the column name OR the column alias if present.
Try this:
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questionID'] . "}"; //this is not the full print
echo "{" . $row['questionText'] . "}"; //just for checking
echo "}";
}
$sql is aparently not set. You can do:
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}

php mysqli select resultset is not showing anything

Ive been trying to crack this for 2 hours, but something is wrong. I am very much used to doing things without mysqli but read that there is a recommended shift towards it from regular mysql commands. Hence am stuck with following:
<?php
$mysqli = new mysqli('localhost', 'admin', 'test123', 'kadmindb');
if ($result = $mysqli->query("SELECT * FROM records WHERE '$queryType' = '$keyword'")) {
while ($row = $result->fetch_object()) {
echo "<h2>Result:</h2><br>";
echo "ID: " . $row->id . "<br>";
echo "Name: " . $row->cust_name . "<br>";
echo "Invoice No: " . $row->invoice_num . "<br>";
echo "Date: " . $row->date_recorded . "<br>";
}
}
?>
This code is shown in the page where the result of the query should be displayed but nothing is displayed. I checked that both keyword and queryType variables are set and they contain the correct values. Any help would be greatly appreciated. All am trying to do is: select statement to retrieve all the details based on invoice_num submitted.
EDIT: from help I received, I was able to get this working:
$query = "SELECT * FROM records WHERE ".$queryType. " LIKE '%$keyword%' ";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_object()) {
echo "<h2>Result:</h2><br><hr/> ";
echo "ID: " . $row->id . "<br>";
echo "Name: " . $row->cust_name . "<br>";
echo "Invoice No: " . $row->invoice_num . "<br>";
echo "Date: " . $row->date_recorded . "<br>";
echo "<hr/>";
}
}
Are you sure there's data to select? This code will only output data if there actually is.
Make sure that $queryType and $keyword are set and have sane values that will yield a result.
Use var_dump($queryType) and var_dump($keyword) immediately before the query. Now check your output. Are they both strings? Run this query directly in PHPMyAdmin and check how many rows you get.
If you can't do that try echo'ing the number of rows returned along with the query values:
if ($result = $mysqli->query("SELECT * FROM records WHERE $queryType = '$keyword'"))
{
while ($row = $result->fetch_object())
{
echo "<h1>Query WHERE '$queryType' = '$keyword' yielded {$result->num_rows} rows!</h1>";
echo "<h2>Result:</h2><br>";
...
Note, you should not have single quotes around the column ($queryType), if you insist you should use backtick quotes (`) but it's unnecessary really - if you're that pedantic you should be using prepared statements.
Also be sure to filter them for any potentially dangerous values that could allow for sql injections. See: mysqli::real_escape_string
Assuming that $queryType is the name of a column in your records table, then I believe the problem is your WHERE clause.
Rather than:
$mysqli->query("SELECT * FROM records WHERE '$queryType' = '$keyword'")
You should have:
$mysqli->query("SELECT * FROM records WHERE {$queryType} = '{$keyword}'")
Note that I've removed the single quotes around $queryType and have used complex (curly) syntax
Also, in the future you might want to try using an else block to trap errors:
$mysqli = new mysqli('localhost', 'admin', 'test123', 'kadmindb');
if ($result = $mysqli->query("SELECT * FROM records WHERE {$queryType} = '{$keyword}'")) {
while ($row = $result->fetch_object()) {
echo "<h2>Result:</h2><br>";
echo "ID: " . $row->id . "<br>";
echo "Name: " . $row->cust_name . "<br>";
echo "Invoice No: " . $row->invoice_num . "<br>";
echo "Date: " . $row->date_recorded . "<br>";
}
}
else
{
echo "Error: " . $mysqli->error;
}

Categories