echo something out MySQL database - php

I am trying to get a question with answers out of my database. I just want to get one thing out of the database and not with a row. I thought this would work but it puts out this: Resource id #4 can someone explains what I am missing.
Thanks :)
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysql_query($sql);
echo $test;
?>

As said at least 10000 times everywhere in internet, never use MySQL_ ! (If your are trying to learn something new by using tutorials over internet, don't use old ones)
I recommend to use PDO which is modern API in PHP and a lot more secure when using it correctly with prepared statement ! But you can also use MYSQLI which is more similar to the MYSQL !
You have to export your data from return array :
Using PDO :
$db = new PDO ("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
$query = $db -> prepare ("SELECT * FROM vraag1");
$query -> execute (array ());
$rows = $query -> fetchAll (PDO::FETCH_ASSOC);
foreach ($rows as $row)
{
echo $id = $row["id"];
echo $vraag = $row["vraag "];
echo $AntwA = $row["AntwA "];
echo $AntwB = $row["AntwB "];
echo $AntwC = $row["AntwC "];
echo $AntwD = $row["AntwD "];
}
Using MYSQLI :
$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$query = "SELECT * FROM vraag1";
$rows = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($rows))
{
echo $row["id"];
echo $row["vraag"];
echo $row["AntwA"];
echo $row["AntwB"];
echo $row["AntwC"];
echo $row["AntwD"];
}

First of all the mysql function you are using is depreciated and no longer supported. you should use mysqli or pdo instead with prepared statements.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "lotto";
// Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1";
$test = mysqli_query($conn, $sql);
if (mysqli_num_rows($test) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($test)) {
echo "ID : ".$row['id']."<br>";
echo "vraag :".$row['vraag']."<br>";
echo "AntwA :".$row['AntwA']."<br>";
echo "AntwB :".$row['AntwB']."<br>";
echo "AntwC :".$row['AntwC']."<br>";
echo "AntwD :".$row['AntwD']."<br>";
}
} else {
echo "no results found";
}
mysqli_close($conn);
?>

For select function mysql_query() returns a resource on success, or FALSE on error.
so your assignment statement
$test = mysql_query($sql);
assign the resource to $test.
if you want the data inside the resource you can do
while($row= mysql_fetch_assoc($test)):
print_r($row);
endwhile;
also you can access the $row['column_name']
If you want to return only one row you can do this limit in query
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1 limit 1';

You need to add something like the following:
while($row = mysql_fetch_array($result)){
echo $row['id'];
echo $row['vraag'];
echo $row['AntwA'];
echo $row['AntwB'];
echo $row['AntwC'];
echo $row['AntwD'];
}

use mysqli instead of mysql
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysqli_query($sql);
echo $test;
?>

Related

autocomplete return '0 results'

recently started coding, tried to use prepared statements for the first time, but it's returning '0 results' and I can't find the error.
Autocomplete was working without prepared statements, but don't know where I'm going wrong now.
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName= "vlucht";
$mysqli = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($mysqli, 'utf8');
$id = $_GET['q'];
$disc = "%" . strtolower($id) . "%";
$sql = "SELECT DISTINCT postgemeente FROM overzicht WHERE LOWER (postgemeente) LIKE ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $disc);
$stmt->execute();
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["postgemeente"]. "\n";
}
} else {
echo "0 results";
}
$mysqli->close();
?>
If you are using prepare->bind->execute ..... you need to remove this line
$result = $mysqli->query($sql);
See comments
<?php
// help with debugging
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName= "vlucht";
$mysqli = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($mysqli, 'utf8');
$id = $_GET['q'];
$disc = "%" . strtolower($id) . "%";
$sql = "SELECT DISTINCT postgemeente FROM overzicht WHERE LOWER (postgemeente) LIKE ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $disc);
$stmt->execute();
// remove you are doing it differently now
//$result = $mysqli->query($sql);
// add to get a result object from a statement object
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["postgemeente"]. "\n";
}
} else {
echo "0 results";
}
$mysqli->close();
?>

PHP mysqli query doesn't return any results

I'm using this code here
<?php
error_reporting(1);
$servername = '127.0.0.1';
$username = '';
$password = '';
$dbname = 'splafpoo_users';
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
printf("<b>Connection failed:</b> %s\n", mysqli_connect_error());
exit;
}
$key = '';
if(isset($_POST['key'])){
$key = $_POST['key'];
}
$query = "SELECT * FROM users WHERE serial='$key'";
echo $query;
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
echo $row;
?>
Running the query SELECT * FROM users WHERE serial='test' in phpMyAdmin returns the desired result however when trying to display the result using the code above nothing is displayed and I cannot figure out how. How do I display the result?
You're gonna need a good old fashion while loop
while($row = $result->fetch_assoc()) {
echo $row['WHATEVERCOLUMNITISYOUWANT'];
}
also this is most definitely a duplicate.
Use var_dump($row) instead of echo $row or you use echo with a key:e.g. echo $row["user"]

How to show table from MySQL database using php and html

I am trying to connect my html page with MySQL database to show data from one specific table to my page, but I always get an error actually it just goes to die part of an SQL code. I am really new to PHP programming so please can someone help me, what am I doing wrong?
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AJDE</title>
</head>
<?php
$servername = "localhost";
$username = "******";
$password = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "select * from PERCENTILE";
$result = mysqli_query($conn,$query);
if(!$result) {
die ("Umro!");
}
/* close connection */
$mysqli->close();
?>
<body>
</body>
</html>
Thank you!
Do you want to show the table as a HTML table or just an array?
The following is what I did to display my table as a HTML table:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
echo("<div class = 'data_wrapper'>");
// Display Header of the table
$fieldcount=mysqli_num_fields($result); //value = number of columns
$row = mysqli_fetch_assoc($result); //Fetch a result row as an associative array:
//array to string conversion
echo("<table id='example' class='table table-striped table-bordered' cellspacing='0' width='100%'>");
echo("<thead> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </thead>");
//Footer
echo("<tfoot> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </tfoot>");
//Display Data within the table
echo("<tbody>");
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
foreach ($row as $item){
echo "<td contenteditable = 'true'>" . $item . "</td>"; //Change contenteditable later
//Editable data should be constricted, int = numbers only, string = words, date = date
}
echo "</tr>";
}
echo("<tbody>");
echo "</table>";
echo("</div>");
}
The following is just displaying as an array:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
while ($row = mysqli_fetch_array($result)){
print_r($row);
}
}
Please change the connection string like mentioned below.
<?php
$con = mysqli_connect("localhost","username","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Please let me know if you've any queries.
I Think you need to select a database where you will run the query:
Try with this code:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with (so replace the database name examples)
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM PERCENTILE");
//fetch the data from the database and display results
//replace id,name,year with the columns you have on your table PERCENTILE and you want to show
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name'}."Year: ". $row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
Hope it helps,
Vince.

How can I print all my database row from PHP?

I am trying to print all the rows in my database say 'student'. I am trying with many of codes with while loops and even examples from w3school. But, it's not working. Here's a simple code of php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect to MySql'.mysql_error());
}
mysql_select_db("StudDatabase") or die(mysql_error());
$sql = "SELECT * FROM Student";
mysql_query($sql);
mysql_close($conn);
?>
I am working in wamp server 2.2
Your code don't print the result of the query.
Try to add this code:
$results = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($results)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
But you should consider using PDO, mylsql is deprecated : http://php.net/manual/en/pdo.connections.php
$database = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($database->query('SELECT * FROM `Student`') as $row) {
print_r($row);
}

Converting my deprecated mysql to mysqli

I'm a beginner here I need to learn the basic in converting from mysql to mysqli. I want to start in configuration first. I have used this connect.php and it's working now I wanted to switch to undeprecated mysqli. Please advise me how to modify this script.
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "nopassword";
$dbname = "student";
$link_id = mysql_connect($host, $dbusername, $dbpassword);
if(!$link_id){
die(mysql_error("Can`t Connect To database"));
}
else{
$db = mysql_select_db($dbname, $link_id);
}
if(!$db){
die(mysql_error("Can`t select database"));
}
return;
?>
According to my comment....
you could do it that way
$host = "localhost";
$dbusername = "root";
$dbpassword = "nopassword";
$dbname = "student";
$link = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link));
$query = "SELECT knowhow FROM google WHERE myknowhow='leaks'";
$knowhow = mysqli_query($link, $query);
this is just the simplest way you can do it.
But you should use it like this (OOP)
$db = new mysqli($host,$dbusername,$dbpassword,$dbname);
$knowhow = $db->query("SELECT knowhow FROM google WHERE myknowhow='leaks'");
According to your comment:
You dont need the IF/ELSE statements anymore. All errors are catched with
die("Error " . mysqli_error($link));
In the oop, errors are catched in
... new mysqli($host,$dbusername,$dbpassword,$dbname);
EDIT
Since you where blocked asking new questions ill just update this answere:
$link = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link));
$query = "SELECT * FROM student_information where student_id='{$_SESSION['user_id']}'";
$knowhow = mysqli_query($link, $query);
$data = mysqli_fetch_array($result);
$numRows = mysqli_num_rows($result);
$i = 0;
while($i < $numRows){
echo $data[$i++] . "<br />";
}
// I would not use a while in this case. I would prefere a foreach
// just to prevent from using a endless loop and 1 row less code :)
foreach($data as $d){
echo $d . "<br />";
}
Please use MySqli as a Class like $db = new Mysqli();

Categories