How can I print all my database row from PHP? - 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);
}

Related

PHP error: Why isn’t this working, I can't see data result in my page?

I'am setting up a new wampserver and created a new database with a table named 'users'
apache 2.4.23 & PHP 7.1.10 & mySQL 5.7.14
<?php
$server = 'localhost';
$serverUsername = 'root';
$serverPassword = '';
$dbName = 'test';
$connection = mysqli_connect($server,$serverUsername,$serverPassword);
msqli_select_db($dbName);
if(!$connection){
echo 'connection failed to database '.mysqli_connect_error();
}
$sql = "SELECT * FROM users";
$query = mysqli_query($sql);
while($row = mysqli_fetch_array($query)){
print_r($row);
}
?>
my value is really in th data base but nothing appears in the page after running code
Have a look at the comments mentioning the fix
$server = 'localhost';
$serverUsername = 'root';
$serverPassword = '';
$dbName = 'test';
// FIX 1
// You need to mention the database name as the last argument
$connection = mysqli_connect($server,$serverUsername,$serverPassword, $dbName);
if(!$connection){
echo 'connection failed to database '.mysqli_connect_error();
}
$sql = "SELECT * FROM users";
// FIX 2
// The first argument should be your mysqli connection
$query = mysqli_query($connection, $sql);
// Check for errors
if (!$query) {
printf("Error: %s\n", mysqli_error($connection));
exit();
}
while($row = mysqli_fetch_array($query)){
print_r($row);
}
?>
Reference for mysqli_connect: https://secure.php.net/manual/en/function.mysqli-connect.php
Reference for mysqli_query: https://secure.php.net/manual/en/mysqli.query.php

echo something out MySQL database

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

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.

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

Import data from mdb file to mysql database can not upload data

I'm using PHP code to upload or insert data from MDB file to MySQL database.I want my table value get inserted into MySQL database. But data does not inserted into MySQL database.This code shows me no error.Here is my code. please help I have tried every solution on net.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'payroll_system';
//mysql
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
$sql = "SELECT * FROM attendance";
$result = mysql_query($sql);
//mdb
$conn2 = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn2->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=C:\\xampp\\htdocs\\payroll\\eTimeTrackLite1.mdb");
$rs = $conn2->Execute("SELECT * FROM AttendanceLogs");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$column1=$row["AttendanceLogId"];$column2=$row["AttendanceDate"];$column3=$row["EmployeeId"];$column4=$row["InTime"];
$column6=$row["OutTime"];$column8=$row["Duration"];
echo "hello";
echo $column1;echo $column2;echo $column3;echo $column4;
$rs->MoveFirst();
while (!$rs->EOF)
{
$attendance_id = $rs->Fields("AttendanceLogId");
$attendance_date = $rs->Fields("AttendanceDate");
$emp_id = $rs->Fields("EmployeeId");
$in_time = $rs->Fields("InTime");
$out_time = $rs->Fields("OutTime");
$duration = $rs->Fields("Duration");
mysql_query("UPDATE attendance SET AttendanceLogId = '$attendance_id', AttendanceDate='$attendance_date', EmployeeId='$emp_id',InTime='$in_time',OutTime='$out_time',Duration='$duration' '"); ?>
<?php
$rs->MoveNext();
}
}
?>
</table> <?php
mysql_free_result($result);
$rs->Close();
$conn2->Close();
$rs = null;
$conn2 = null;
?>
you need to INSERT each records data instead of UPDATE. Re-write the following line:
mysql_query("UPDATE attendance SET AttendanceLogId = '$attendance_id', AttendanceDate='$attendance_date', EmployeeId='$emp_id',InTime='$in_time',OutTime='$out_time',Duration='$duration' '");

Categories