Select and print out Data from MySQL with php, not working - php

I have a table ("module databas") in a database in MySQL and I need to print out that table (very simple, two rows "Fnamn" and "Enamn" with names in it) on the server by writing a php script and using MySQL. Problem is : it doesn't work. The html part of the document (.php) works perfectly fine (the h1 appears on the screen) but I get nothing else. What could be the problem ?
Tried a few different ways to do it, even by copy/pasting from w3 schools (https://www.w3schools.com/php/php_mysql_select.asp) and changing a few variables, but nothing (had a "0 results" with this W3 one, and now nothing with the new one).
<h1>Script modul</h1>
<?php
$servername = "localhost";
$username = "antony";
$password = "thepassword";
$dbname = "antony";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM moduledatabas";
$result = mysqli_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysqli_fetch_assoc($result)) {
echo $row['Fnamn'];
echo $row['Enamn'];
}
mysqli_free_result($result);

You have not pass $conn in your mysqli_query(),just change your code like below :
$query = "SELECT * FROM moduledatabas";
$result = mysqli_query($conn,$query);
For more info refer mysqli_query

Related

How to use ? in URL?

I am trying to figure out a way to have one PHP page to display all of my blog post but have the URL decide what post is requested from that database. Something kind of like this: localhost/bolg/posts.php?pid=1 In my database I have it set up to where each post has an ID associated with it. So what I want is something that put the pid=1 and put it in the MySQL code. Here is the PHP code of the post.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title, content, date FROM posts where id =3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Assuming you enter example.com?pid=10 in the browser address bar, you can capture that variable pid using the $_GET (docs) array which PHP automatically fills for you when a page is called with a querystring.
Using your existing code as a start point you can
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
if (isset($_GET['pid'])) {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, title, content, date FROM posts where id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['pid']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// output data of each row
// while looop is not necessary, you are only returning one row
$row = $result->fetch_assoc();
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
$conn->close();
} else {
echo "0 results";
}
Notice I took the liberty of amending your database access code to use prepared and parameterised query and binding the values to avoid SQL Injection Attack. You should always use this technique in the future

Select SQL query is not working in PHP

I am having trouble with an SQL query that I have inserted into a piece of PHP code to retrieve some data. The query itself works perfectly within SQL. I am using the following PHP script.
I have the following objectives:
Connect to the existing database. This part works well.
Get data from the column 'Brand' of the table 'Transport' in $sql. This part is not working at this stage. echo ($sql) returns SELECT Brand FROM Transport WHERE Type = 'car'
Could you please let me know if you see the solution to this issue and if the remaining part of the code is correct. This is my f_sqlConnect()
function f_sqlConnect() {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: '.mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can not use'.DB_NAME.
': '.mysql_error());
}
}
/*This function cleans up the array to protect against injection attacks */
function f_clean($array) {
return array_map('mysql_real_escape_string', $array);
}
<?php
// Create connection
$link = f_sqlConnect();
// Getting data from the column Brand of the table Transport
$sql = "SELECT Brand FROM Transport WHERE Type = 'car'";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Brand: " . $row["Brand"]. "<br>";
}
} else {
echo "0 results";
}
$link->close();
?>
Here is the code, without seeing your f_sqlConnect(); mothod. This method should return connection string for DB in your case. But you can use following code this must work.
<?php
$servername = "Your_db_host";
$username = "your_db_username";
$password = "your_db_password";
$dbname = "your_DB_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Brand FROM Transport WHERE Type = 'car'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Brand: " . $row["Brand"];
}
} else {
echo "0 results";
}
$conn->close();
?>
NOTE: Object oriented way of mysqli, You can use procedural way too to connect and get data.

SELECT COUNT if statement

Ok, so it seems like my SELECT count query doesn't work here:
<?php
$servername = " ";
$username = " ";
$password = " ";
$dbname = " ";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submitted1'])) {
$result= mysqli_query("SELECT COUNT (Motspillerid)
FROM SESSION
WHERE Motspillerid= 3 ");
echo $result ;
} else {
echo "Wrong" ;
}
?>
And when I press submitt nothing happens, I don't get any error message and I don't get the result. So it's something wrong with the SELECT query I guess.
I'm noob I know, I'm new to this.
:)
You're not calling mysqli_query() correctly, the first argument has to be the database connection object returned by mysqli_connect.
And after performing the query, you have to fetch the results using one of the mysqli_fetch_X() functions.
if (isset($_POST['submitted1'])) {
$result= mysqli_query($conn, "SELECT COUNT(*) AS count
FROM SESSION
WHERE Motspillerid= 3 ");
$row = mysqli_fetch_assoc($result);
echo $row['count'];
} else {
echo "Wrong" ;
}

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

not able to show all records in my database

i am testing my database by executing some MySQLi statements
in this case : i want to display all the records of 2 specefic rows (name,score)
i checked how to do such thing in PHP , and i did it
problem is , the page is not showing anything at all , (blank empty page)
My code :
<?php
$servername = "sql3.freesqldatabase.com";
$username = "MY USERNAME";
$password = "MY PASSWORD";
$dbname = "MY DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name,score FROM Scores");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " " . $row["score"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
and , i executed the same query in phpMyAdmin Control Panel , and it worked
What have i done wrong ?
This line
$sql = "SELECT name,score FROM Scores");
Should be
$sql = "SELECT name,score FROM Scores";
This syntax error will cause an error and your environment is likely suppressing errors/warnings.

Categories