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

<?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 ;-) )

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 :(

mysqli statement does not work under php

There's a bit problem for mysqli select statement as I did a select statement which actually counts the number of results. But it does not return the value I want but instead it returns none. Need help guys. I did this select statement as a function using mysqli and php
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
echo "string</br>";
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['userssss']."asdasd</br>";
die("userssss");
$return = $row['user'];
return $return;
}
result
string
asdasd
userssss
It should show the result before asdasd
add global $con;
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as user from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['user'][0]."asdasd";
die();
$return = $row['user'][0];
return $return;
}
I found it. Silly of me.
Instead of using assoc, one must use array
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$return = $row['user'];
return $return;
}
You need to count everything meaning rows matched where clause. Also try to adopt prepared statements. Bellow code works.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function count_result($data){
$user = 'username';
$password = 'password';
$db = 'database';
$host = 'hostname';
$port = 3306;
/* Attempt MySQL server connection. Assuming you are running MySQL server */
$link = mysqli_connect($host, $user, $password, $db);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if($stmt = $link -> prepare("SELECT COUNT(*) FROM test WHERE ID= ?"))
{
/* Bind parameters, s - string, b - blob, i - int, etc */
$stmt -> bind_param("i", $data);
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($testfield1);
/* Fetch the value */
$stmt -> fetch();
$numberofrows = $stmt->num_rows;
} else{
echo "ERROR: Could not able to execute SQL. " . mysqli_error($link);
}
/* Close statement */
$stmt -> close();
echo '# rows: '. $numberofrows . PHP_EOL;
echo 'Count = '. $testfield1 ;
}
count_result(24);
?>
A silly mistake in your code :
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
echo "string</br>";
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['user']."asdasd</br>"; // did changes on this line
die("userssss");
$return = $row['user'];
return $return;
}

Query MySQL with 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)) {

Filter results by date in timestamp field

I have already had some help but not sure why this isn't working.
I am trying to use a form to let a user filter their activity (which is stored in a DB)
My code:
$_GET['from'] = '01/11/2013';
$_GET['to'] = '25/11/2013';
$from = DateTime::createFromFormat('d/m/Y', $_GET['from']);
$to = DateTime::createFromFormat('d/m/Y', $_GET['to']);
$sql = "
SELECT * FROM transfer
WHERE personID = $user AND DATE(time) BETWEEN '%s' AND '%s'
";
$sql = sprintf($sql, $from->format('Y-m-d'), $to->format('Y-m-d'));
print_r($sql);
This prints
SELECT * FROM transfer WHERE personID = 84587749 AND DATE(time) BETWEEN '2013-11-01' AND '2013-11-14'
When I query this in PHPmyadmin it shows the record, however not showing in my page?
The SQL looks fine but you don't appear to have issued the executed the SQL query in the database and retrieved the results?? Maybe I'm missing something but you need to connect to your database:
class DBi {
public static $mysqli;
}
DBi::$mysqli = new mysqli('servername', 'database', 'password', 'user');
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
Then you need to perform the query:
$result = DBi::$mysqli->query($sql) or die ("Unable to execute SQL command:".$sql);
And finally, retrieve and use the result:
$row = $result->fetch_assoc();
echo $row["fieldname"];
Here is an example how you print out your results.
$dbserver = "localhost";
$dbname = "nameofDB";
$dbusername = "username";
$dbpassword = "password";
$mysqli = new mysqli($dbserver, $dbusername, $dbpassword, $dbname);
$query = "SELECT * FROM transfer WHERE personID = 84587749 AND DATE(time) BETWEEN ? AND ?";
if($stmt = $mysqli->prepare($query)){
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$to = $_POST['to'];
$from = $_POST['from'];
$stmt->bind_param('ss', $from, $to);
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Configure this how you want to print out each row.
echo 'Details: '.$row['details'].'<br>';
echo 'Time: '.$row['time'].'<br>';
echo 'Balance: '.$row['balance'].'<br>';
echo '<br><br>';
}
/* free results */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();

php switching to mysqli: num_rows issue

I recently started updating some code to MySQL improved extension, and have been successful up until this point:
// old code - works
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo $row['data'];
}
// new code - doesn't work
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");
if($result->num_rows == 1) {
$row = $result->fetch_array();
echo $row['data'];
}
As shown I am trying to use the object oriented style.
I get no mysqli error, and vardump says no data... but there definitely is data in the db table.
Try this:
<?php
// procedural style
$host = "host";
$user = "user";
$password = "password";
$database = "db";
$link = mysqli_connect($host, $user, $password, $database);
IF(!$link){
echo ('unable to connect to database');
}
ELSE {
$sql = "SELECT * FROM data_table LIMIT 1";
$result = mysqli_query($link,$sql);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $row['data'];
}
}
mysqli_close($link);
// OOP style
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table LIMIT 1";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
if($result->num_rows == 1) {
$row = $result->fetch_array();
echo $row['data'];
}
$mysqli->close() ;
// In the OOP style if you want more than one row. Or if you query contains more rows.
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
while($row = $result->fetch_array()) {
echo $row['data']."<br>";
}
$mysqli->close() ;
?>
As it was said, you're not checking for the errors.
Run all your queries this way
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");
if no errors displayed and var dumps are saying no data - then the answer is simple: your query returned no data. Check query and data in the table.
In PHP v 5.2 mysqli::num_rows is not set before fetching data rows from the query result:
$mysqli = new mysqli($host,$user, $password, $database);
if ($mysqli->connect_errno) {
trigger_error(sprintf(
'Cannot connect to database. Error %s (%s)',
$mysqli->connect_error,
$mysqli->connect_errno
));
}
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql);
// a SELECT query will generate a mysqli_result
if ($result instanceof mysqli_result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$num_rows = $result->num_rows; // or just count($rows);
$result->close();
// do something with $rows and $num_rows
} else {
//$result will be a boolean
}
$mysqli->close() ;

Categories