Getting Data From Multiple MySQL Tables Using PHP and mysqli - php

I am trying to draw data from multiple tables that have been indexed to relate to one another. I ran this query in MySQLWorkbench, and it ran successfully. However when I tried to run a PHP test, nothing showed up, not even for the first field. Here is my code:
<?php
$db = new mysqli('host', 'user', 'password', 'database');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "
SELECT
`Contact`.`firstName`,
`Contact`.`lastName`,
`ssn`.`ssn`,
`Contact`.`country`,
`Allergies`.`allergy`,
`Allergies`.`allergyType`,
`Allergies_Contact`.`allergyNotes`,
`CurrentPrescriptions`.`prescriptionName`,
`CurrentPrescriptions`.`prescribedDate`,
`BloodType`.`bloodType`
FROM
`database`.`Contact`,
`database`.`Allergies_Contact`,
`database`.`Allergies`,
`database`.`ssn`,
`database`.`CurrentPrescriptions`,
`database`.`BloodType`
WHERE
`Contact`.`contactKey` = `Allergies_Contact`.`contactKey`
AND `Allergies`.`allergiesKey` = `Allergies_Contact`.`allergiesKey`
AND `ssn`.`contactKey` = `Contact`.`contactKey`
AND `CurrentPrescriptions`.`contactKey` = `Contact`.`contactKey`
AND `BloodType`.`contactKey` = `Contact`.`contactKey`;
";
$result = $db->query($query) or die($db->error.__LINE__);
if ($result = mysqli_query($db, $query)) {
while ($row = mysqli_fetch_row($result)) {
print(row[0]);
}
mysqli_free_result($result);
}
mysqli_close($db);
?>
Please tell me what I am doing wrong here, because from what I can see its formatted correctly.

Several things:
1.- You have two query sentences, change:
$result = $db->query($query) or die($db->error.__LINE__);
if ($result = mysqli_query($db, $query)) {
With this
$result = $db->query($query) or die($db->error.__LINE__);
if ($result !== false) {
2.- Yo made a mistake when trying to print the variable, change:
while ($row = mysqli_fetch_row($result)) {
print(row[0]);
}
With this
while ($row = mysqli_fetch_row($result)) {
print($row[0]); // You missed a $
}

<?php
//conection:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
//consultation:
$query = "SELECT name FROM mytable" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
//display information:
while($row = mysqli_fetch_array($result)) {
echo $row["name"] . "<br>";
}
?>
http://php.net/manual/en/function.mysqli-connect.php

Related

php-mysql count() query repeating results

Using count() query with php will cause the result display in looping. How to fix this issue?
phpmyadmin has no problem showing the sum but can't apply it to php code.
$conn = mysqli_connect('localhost','root','','db');
if (!$conn) { die('db error'); };
$result = mysqli_query($conn, '
select count(*) as x from users
');
$row = mysqli_fetch_assoc($result);
echo $row['x'];
Expect result :
2
Actual output :
2222222222222222222222222222222222222222222222222222222222222222222...
I recommend you to use prepared statements.
$conn = new mysqli("localhost", "root", "", "db");
if($stmt = $conn->prepare("SELECT count(*) as x FROM users")) {
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$number = $row['x'];
}
$stmt->close();
}else{
echo "Error";
}
$conn->close();
if(isset($number)){
echo $number;
}

Table 'databasename.info' doesn't exist

So I installed this jackpot script with a layout and everything and within the jackpot script there was a set.php file which I tried to set up, it looked like this:
<?php
$sitename = "csgoxd.net";
$link = #mysql_connect("localhost:3306", "csgoxdne", "thisisasecretpassword");
$db_selected = mysql_select_db('csgoxdne_csgoxddb', $link);
mysql_query("SET NAMES utf8");
function fetchinfo($rowname,$tablename,$finder,$findervalue) {
if($finder == "1") $result = mysql_query("SELECT $rowname FROM $tablename");
else $result = mysql_query("SELECT $rowname FROM $tablename WHERE `$finder`='$findervalue'") or die (mysql_error());
$row = mysql_fetch_assoc($result);
return $row[$rowname];
}
?>
So I'm new when it comes to coding in general (I know some basic stuff but that's it) so basically I'm not sure if I'm supposed to fill out more of this file because I get this error on my website.
"Table 'csgoxdne_csgoxddb.info' doesn't exist"
I'm new to this and I'm trying to learn so help is much appreciated.
You should use MySQLi to make use of its advantages it offers over MySQL. You can see more here.
The script you have isn't all too bad, but it does need some tweaking. It's vulnerable to injection like Marc B said. I'm going to assume that csgoxdne_csgoxddb is your table name.
Try this:
<?php
$mysqli = new mysqli("localhost:3306", "csgoxdne", "thisisasecretpassword");
if (mysqli -> error){ print ("Error connecting! Message: ".$mysqli->error); }
mysqli_set_charset($mysqli, 'utf8');
function fetchinfo($rowname, $tablename, $finder, $findervalue) {
if ($finder == "1") {
$query = "SELECT * FROM $tablename WHERE rowname = '$rowname'";
$result = mysqli_query($mysqli, $query);
} else {
$query = "SELECT * FROM $tablename WHERE `$finder`='$findervalue'";
if (!$query) {
die('Invalid query: ' . $mysqli->error);
}
$result = mysqli_query($mysqli, $query);
}
return $result;
}
?>
Oh and make sure the port number on your localhost is correct.
Also to go through the values of result you can use:
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
#do things
}
}

PHP code to encode DB data in JSON not working

I'm currently stuck with some PHP code. I want to access a table in my database and retrieve the data in a JSON format. Therefore, I tried the following code :
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysql_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
However, it's getting me an empty page. It worked once but only with a special number of row in the table, so not very efficient as you might guess.
Does anybody have an idea why i'm getting those weird results?
EDIT 1 :
I Just tried to add this to my code :
echo json_encode($resultArray);
echo json_last_error();
And it's returning me 5. It seems to be an error from the data encoding in my table. Therefore I added that code :
$tempArray = array_map('utf8_encode', $row)
array_push($resultArray, $tempArray);
And I got the following output : [null,null,null]0 (The zero comes from the echo json_last_error();)
So here I am, can anybody help me with this ?
I would start by changing if ($result = mysql_query($con, $sql)) to if ($result = mysqli_query($con, $sql)) because they are different database extensions
Another thing would be to change while($row = $result->fetch_object()) to while ($row = mysqli_fetch_object($result)) { (Procedural style vs. Object oriented style)
If you still see blank screen, try adding error_reporting(E_ALL); at the top of your script, and you'll be able to know exactly where the bug is
<?php
$con = mysqli_connect("......","username","pwd","DBName")
or die("Failed to connect to MySQL: " . mysqli_connect_error());
$sql = "SELECT * FROM users";
$query = mysqli_query($con, $sql) or die ("Failed to execute query")
if ($result = $query)
{
$resultArray = array();
while($row = $result->fetch_object())
{
array_push($resultArray, $row);
}
$result->close()
echo json_encode($resultArray);
}
mysqli_close($con);
?>
This code works for me, try it out:
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysqli_query($con, $sql))
{
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
EDIT 1:
As a test replace this code:
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
with this code:
while($row = $result->fetch_assoc())
{
print_r($row);
}
What output do you get?
I finally found a solution ! That was indeed an encoding problem, the json_encode() function accepts only strings encoded in utf8. I changed the interclassement of my table to utf8_general_ci and I modified my code as follows :
<?php
//Create Database connection
$db = mysql_connect(".....","username","pwd");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("DBName",$db);
//Replace * in the query with the column names.
$result = mysql_query("SELECT * FROM users", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['name'] = utf8_encode($row['name']);
$row_array['lastName'] = utf8_encode($row['lastName']);
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
And I got the expected output.

PHP select one data from mysql NOT DISPLAYING

I am trying to display or return the Date value from a selected user
function mysql_select_one_data($database, $table, $data, $country, $phone){
$conn = mysql_connect("localhost", "root", "test123");
mysql_select_db($database, $conn) or die (mysql_error());
$query = "SELECT DATE FROM Temp_Users WHERE Country = '+94' AND Phone = '1234539543';";
$result = mysql_query($query) or die (mysql_error());
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_assoc($result)) {
echo "Date: " . $row["Date"]. "<br>";
}
} else {
echo "0 results";
}
return $result;
}
result:
Date:
Resource id #5
but when I do the query in phpmyadmin it returns
I am new in Php and I Don't know what I am doing wrong, Thanks for your help.
change this
$query = "SELECT DATE FROM Temp_Users WHERE Country = \"+94\" AND Phone = \"1234539543\";";
to this
$query = "SELECT DATE FROM Temp_Users WHERE Country = '+94' AND Phone = '1234539543';";
Change the echo command to echo "Date: $row['DATE']<br>"

Adding title in PHP

I would like to add, let's say, some kind of a title. My PHP returns something like this:
[{"Grad":"Beograd","Predmet":"matematika"},{"Grad":"Novi_Sad","Predmet":"matematika"},{"Grad":"Beograd","Predmet":"matematika"}]
And I would like to get something like this
{"lista"[{"Grad":"Beograd","Predmet":"matematika"},{"Grad":"Novi_Sad","Predmet":"matematika"},{"Grad":"Beograd","Predmet":"matematika"}]}
This is my PHP
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT Grad, Predmet FROM lista";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
$rows = (object) array('lista' => $rows);
echo json_encode($rows);
Something like this: $rows['lista'][] = $row ?

Categories