Get values from mysql database and store in php array [duplicate] - php

This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 5 years ago.
I am working on a project with php and Mysql where I need to get values from Mysql database and store them into array.
Code:
$con=new mysqli("localhost","root","","databse");
$sql="select name from data";
$result= array();
$result=$con->query($sql);
How to store the data in php array?

Here is an example of how to do it!
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
$sql = mysqli_query($connection, "SELECT * FROM data");
while($row = mysqli_fetch_array($sql)) {
$names[] = $row['name'];
}
Edit:
Print the results out by using
print_r($names);
or
foreach($names as $name) {
echo "$name";
}
Good luck!

Related

could not connect to db [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 5 years ago.
Im haveing a problem with this code:
<?php
include 'connect.php';
$SQL = "INSERT into users(username, password, email,)
VALUES ('dado','123','neki#gmail.com',)";
mysql_query($SQL) or die("could not register");
?>
My connect.php looks like this:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'igra';
?>
When I try to exectue it, Im getting error. Tryed testing connection with
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'igra';
$connect = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Unable to connect to dbhost");
mysql_select_db($dbname)
or die("Could not connect to db");
$test_query = "SHOW TABLES FROM $dbname";
$result = mysql_query($test_query);
$tblCnt = 0;
while($tbl = mysql_fetch_array($result)) {
$tblCnt++;
#echo $tbl[0]."<br />\n";
}
if (!$tblCnt){
echo "There are no tables<br />\n";
} else {
echo "There are $tblCnt tables<br />\n";
}
?>
and it return msg: There are 4 tables. Which means connect.php is properly set. Now I tryed to run code into MySQL Admin program itself with "INSERT into" query, and it worked. So, everything seems to work fine separatly, but when put together, it wont work.
Can somebody point me to misstake Im makeing please?

how mysql query written in php to get json format output [duplicate]

This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 6 years ago.
i have written code in php file that to connect to database and get the requested data .
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
$subject = mysqli_fetch_assoc($result);
print_r($subject);
?>
i am getting the output in array format ,i want to get the out put in json format.how to change the code ,please help me .
You need to use php json_encode() method. Please check php doc for json_encode here
Use json_encode:
I suppose you're making API to return JSON string, make sure you return it as a JSON response instead of HTML. It's a good practice :)
To return JSON string as a JSON response, You can do the following.
<?php
header('Content-Type: application/json');
echo json_encode($subject);
?>
create a array or results and use json_encode.
$subject = array();
while($row = $result->fetch_assoc() ){
$subject[] = $row;
}
echo json_encode($subject);
You have to use json_encode($subject).
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
$subject = mysqli_fetch_assoc($result);
if($subject)
{
$json_subject = json_encode($subject);
print_r($json_subject);
}
?>

Echo a mysql column by php as an array [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
i want to fetch a mysql table named "my_table" column named "Email" contents as an array by php , so this is my code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_table";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysql_query("SELECT * FROM my_table");
if ($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row['Email'];
}
echo join($data, ',');
?>
but this code returns me this error :
No database selected
but i've selected my table and database ...
and i know this code have some problems as mixing mysql and mysqli content but i dont know how to fix it i just want that array echo , if this code need to be fixed just guid me ,
how to solve this problem ? thanks in advance
Thanks to #Martin
my problem has solved i just changed the code by this way :
<?php
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "my_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}
$result = mysqli_query($conn, "SELECT * FROM my_table");
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$data = array();
while ($row = mysqli_fetch_array($result))
{
$data[] = $row['Email'];
}
echo join($data, ',')
?>
You are conencting to a database here called "my_table":
$dbname = "my_table";
And then, in your SQL statement, you try connecting to a table called the same:
$result = mysql_query("SELECT * FROM my_table");
Are you sure this is the correct name for your database?
On PHPMyAdmin you can click "Databases" to view the Database names and then, when clicking on the db, it will give you a list of tables:
Image file of getting database views from tables in PHPMyAdmin

Getting error: Object of class mysqli_result could not be converted to string [duplicate]

This question already has an answer here:
How to use mysqli_query() in PHP?
(1 answer)
Closed 6 years ago.
My code is very messy, but I am trying to make a forum on my website.
<?php
$conn = mysqli_connect("localhost", "root", "");
if($conn->connect_error){
die("Connection Failed");
}
mysqli_select_db($conn, 'forum');
$get= "select * from forum";
$runq = mysqli_query($conn, $get);
while($fetch_value=mysqli_fetch_array($runq)){
$get_usr_name=$fetch_value['username'];
$get_body = $fetch_value['info'];
}
$result = $conn->query($get);
if(is_null($get_body)){
}
else{
echo "<div id='inputform1'>";
for($row = 1; $row < $result->num_rows; $row++){
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "forum";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()){
die("database connection failed: ") .
mysqli_connect_errno() .
" (" . mysqli_connect_errno() . ")";
}
$result1 = mysqli_query($connection, "select info from forum where id='$row';");
$result = mysqli_query($connection, "select username from forum where id='$row';");
echo "<strong class=\"after_username\">by: {$result}</strong><br><br><p id=\"bodyforum\">{$result1}<br><br></p>";
}
echo "</div>";
}
?>
I cannot seem to post the username and password; it keeps saying:
Object of class mysqli_result could not be converted to string
I have tried many different "tactics" but none of them seem to work. Can someone help me?
The returned value of a mysqli query is a result object. It's not just a set of rows; it also contains information on the query, success or failure, error messages, and other things. You need to use the result object's methods explicitly to access the rows returned by your query.
I think the problem is from this line
echo "<strong class=\"after_username\">by: {$result}</strong><br><br><p id=\"bodyforum\">{$result1}<br><br></p>";
The $result and $result1 are not strings. You need to loop it up and then access the records.

No database selected help me solve this [duplicate]

This question already has answers here:
PHP "No Database Selected"
(2 answers)
Closed 8 years ago.
hey everyone what's wrong with this :( i get no database selected .. what seems to be the problem ? damn i can't get this right.
<?php
require_once('db.php');
function getLanguage() {
global $db;
global $conn;
$sql = "SELECT * FROM books.languages ORDER BY name ASC";
$db = mysql_connect($hostname, $username, $password);
$rs = mysql_query($sql, $db) or die(mysql_error());
$rows = mysql_fetch_assoc($rs);
$tot_rows = mysql_num_rows($rs);
if($tot_rows > 0){
?>
Problem is no database is selected (didn't I see that in your question ?)
Where is your call to mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )?
It should be after the connect.
$db = mysql_connect($hostname, $username, $password);
mysql_select_db("your_database_name");
$rs = mysql_query($sql, $db) or die(mysql_error());
(obviously you should have error checking too...)
Maybe something like the following will help? I am using MySQLi as MySQL is deprecated.
db.php
<?php
// CONNECT TO THE DATABASE
$DB_NAME = 'database';
$DB_HOST = 'host';
$DB_USER = 'username';
$DB_PASS = 'password';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
Then use the following to query your database.
<?php
require_once('db.php');
$sql = "SELECT * FROM tablename";
$rs = $mysqli->query($sql) or die($mysqli->error.__LINE__);
if($rs->num_rows > 0) {
while($row = $rs->fetch_assoc()) {
//Do Something
}
}
else {
echo 'NO RESULTS';
}
mysqli_close($mysqli);
?>

Categories