Query MySQL with PHP - php

I am trying to query a MySQL database with PHP and return the results as JSON. I'm new to PHP and web development so I'm not sure what I'm doing wrong. I've set up the database using MAMP. My parameters are being printed but I'm not getting the JSON. I've gotten this far with the help of a tutorial.
EDIT: I just went into phpMyAdmin to make sure it was working and when I click on Server:localhost:8889, a window pops up that says Error in processing request. Error code 404.
I'm thinking this is the problem, I'm just not sure why it isn't working. I may reinstall MAMP.
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>

You need to change you $sql variable to remove the escapes on the single quotes. They register as part of the string because you are using double-quotes to wrap it. Basically, you're telling the database to run the query "SELECT * FROM NAME WHERE FIRST_NAME = \'John\' and LAST_NAME = \'Smith\' and MEMBERSHIP_NUMBER = \'VRX78435\'". This will error if you run it directly because the escape characters are not escaping.
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = '$first_name' and LAST_NAME = '$last_name' and MEMBERSHIP_NUMBER = '$membership_number'";
That should fix it for you.
There may also be an issue with your connection to the server. mysqli_query() uses the results of mysqli_connect() to run the query. mysqli_real_connect() only returns a boolean value, so it is invalid for this particular use (at least it failed to work on my server).
This would be a simple matter of replacing the $con and then you can drop the $link variable.
$con = mysqli_connect($host, $user, $password, $db, $port);
These changes, and assuming the $first_name, $last_name, and $membership_number are all valid, allowed your script to run for me, so I hope this helps.

Seems you are using procedural style coding
Instead of
while($row = $result->fetch_object()) {
You need mysqli_fetch_object in procedural style
while($row = mysqli_fetch_object($result)) {

Related

List all the tables in your MySQL database using PHP

I have a hard time trying to list all the tables in my database.
I tried
<?php
//Configuration
$dbname = 'local';
$user = 'root';
$host = '127.0.0.1';
$pass = '';
$date = date('Y-m-d');
$export_type = 'mysql'; // option : mysql | psql
$file_name = $date.'-portal';
$file_path = $file_name;
// Create connection
$conn = mysqli_connect($host, $user, $pass);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SHOW TABLES FROM $dbname";
$res = mysqli_query($conn, $sql);
if($res != false){
echo "Connected successfully";
$FILE = fopen("output.csv", "w");
$table = array();
while($row = mysql_fetch_array($res)){
$table[] = $row['0'];
}
foreach($tables as $table) {
$columns = array();
$res = mysqli_query($conn, "SHOW COLUMNS FROM $table");
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$columns[] = "$row[0]";
}
fwrite($FILE, implode(",", $columns)); fwrite("\n");
$resTable = mysqli_query($conn, "SELECT * FROM $table");
while($row = mysql_fetch_array($resTable, MYSQL_NUM)) {
fwrite($FILE, implode(",", $row)); fwrite("\n");
}
}
}else{
die(mysql_error());
}
?>
Result
if($res != false){
//.. everything in here never get executed
}
`$res` kept returning `false`.
What did I do wrong that could have lead to this ?
You can always execute the query:
Show tables;
After you selected database.
By the way you also can execute:
Show databases;
To list all of the databases your current user has permission to view.
Use db in your connection
mysqli_connect($host, $user, $pass, $dbname);
And use query like this
$sql = "SHOW TABLES";
You need to pass through your database in the connection script.
Like so:
$conn = mysqli_connect($host, $username, $pass, $dbname);
Then, when you want to pull rows from a table, you do it like this:
mysqli_query($conn, "SELECT rows FROM table");
One of the reasons this wasn't working for you was because you weren't passing through your database name through the connection. Also, rather than doing the above query, you selected a table from a database; rather than a row from a table.
Also, I noticed that you're using the mysql_* error output on the last line.
Here is a working version
Changes:
Added $dbname to mysqli_connect function
Added the backtick ` char between the table names, to avoid errors with reserved keyword from MySQL
Changed mysql_ functions to mysqli_
Close the file
Close the connection
Here is the code
NOTE: sorry I don't why, but when I pasted the code in the answer, all de code identation was messed up, even trying to indent it properly, I wasted like 10 minutes :(

phpMyAdmin: one table in database work, another doesn't

I've created an app were you can register as a user. You can sign up and then you're in the database "myAppDataBase" in "firsttable". A second table contains a list of lets say other important users that I manually created in the PHPmyAdmin-Website/"App". This table is called "secondtable".
My code to get the data is as follows:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydatabas";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}else{
//Print ("successfully connected");
}
$query = "SELECT * FROM firsttable";
$result = mysqli_query($conn, $query) or die("Error: " . mysqli_error($query));
$num = mysqli_num_rows($result);
$rows = array();
while ($r = mysqli_fetch_assoc($result))
{
$rows[] = $r;
Print ("sf");
}
Print json_encode($rows);
mysqli_close($conn);
?>
The only thing i changed was this line: THIS WORKS
$query = "SELECT * FROM firsttable";
But when I change it to this it won't work anymore.
$query = "SELECT * FROM secondtable";
Any help?
Change this:
mysqli_error($query)
With this:
mysqli_error($conn) // with your connection
Explanation:
mysqli_error() function needs connection link identifier not your query as param.
Mysqli_error PHP Manual
I SOLVED IT! Somehow, my second wasn't encoded the right way. I simply added this coder and it worked:
mysqli_set_charset($conn, 'utf8mb4');
Thanks for all you help though. ;)

ERROR : fetching data from mysql and showing in on the web

<?php
$user = 'root';
$password = 'root';
$db = 'urls';
$host = 'localhost';
$port = 8889;
$link = mysqli_init();
$success = mysqli_real_connect(
$link,
$host,
$user,
$password,
$db,
$port
);
//echo $success;
$query = "SELECT id, title, url, votes FROM link ORDER BY id LIMIT 3";
$result = mysqli_query($success, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["title"], $row["url"]);
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
So this is the code i wrote. Obviously, the purpose of this is to fetch latest datas from my mysql server and print it out. However, when i run this code on my mac(I'm using MAMP), IT ONLY SHOW '0'. What is wrong with this?
mysqli_real_connect returns a boolean, it does not return a MySQLi resource. Hence you have to run the query on $link and not on $success
$result = mysqli_query($success, $query);
^
Should be
$result = mysqli_query($link, $query);
Without any error checking in place it becomes like a guessing game, please consider error checking whether the connection resulted in an error or the query itself, that will help you a long way.
Also note that you have to either fetch all the rows together in one call (using a different function as to what you use now) or you have to loop through the result to fetch all the rows, with your current code you will get only 1 row at max even when the issue is resolved.
On another note, why are you not using the simpler mysqli_connect option and using this 2 step connection without any special flags being used?
Try it with a bit more error handling
<?php
$user = 'root';
$password = 'root';
$db = 'urls';
$host = 'localhost';
$port = 8889;
echo date('Y-m-d H:i:s', filemtime(__FILE__)), "\r\n";
$link = mysqli_init();
if ( !mysqli_real_connect($link, $host, $user, $password, $db, $port) ) {
trigger_error('connect failed', E_USER_ERROR);
}
else {
$query = "SELECT id, title, url, votes FROM link ORDER BY id LIMIT 3";
$result = mysqli_query($link, $query); // <- you have to pass the connection resource/object here
if ( !$result ) {
trigger_error('query failed', E_USER_ERROR);
}
else {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if ( !$row ) {
echo 'no results';
}
else {
do {
printf ("%s (%s)\n", $row["title"], $row["url"]);
} while($row = mysqli_fetch_array($result, MYSQLI_ASSOC));
}
/* free result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
}
( the echo date... line is for checking that you're looking at the output of your latest and greatest script version ;-) )

Why do I encounter Internal Server Error while converting MySql TO MySQLi?

I've tried searching for answers and used some tutorials, but nothing
has helped.
I can successfully establish a connection to my database.
But when I try to run this query, I get 500-Internal Server Error.
The code I am using is:
$stmt = $conn->prepare("SELECT * FROM people WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows):
$row = $stmt->fetch_assoc();
$id = $row['id'];
$position = $row['position'];
else:
die("User not found.");
endif;
How I used to do it using MySQL:
$sql = "SELECT * FROM people WHERE name = '$name'";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) > 0):
$row = mysql_fetch_array($result);
$id = $row['id'];
$position = $row['position'];
else:
die("User not found.");
endif;
Any and all help will be appreciated.
EDIT: The following code is at the start of my file:
// Connection Details
$host = "";
$user = "";
$pass = "";
$db = "";
// Database Connection
$conn = new mysqli($host, $user, $pass, $db);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
Could you please tell me the best way to replicate the MySQL code I posted in MySQLi?

PHP MySQLi echo data in array without doing a while loop

When using MySQLi, do I have to perform a kind of while loop where the actual data from the query is put into a variable array?
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// Check if able to connect to database
if ($conn->connect_error) {
trigger_error("Database connection failed: " . $conn->connect_error, E_USER_ERROR);
}
$sql = "SELECT name FROM users WHERE email = '$email'";
$rs = $conn->query($sql);
$numRows = $rs->num_rows();
I always do the following:
$rs->data_seek(0);
while($row = $rs->fetch_assoc()) {
$name = $row['name'];
}
echo $name;
Isn't there a much more convenient way to echo the data form the query when there is only one row?
If there is only one row, you don't need the loop. Just do:
$row = $rs->fetch_assoc();
$name = $row['name'];

Categories