Why can't i echo my results from MySQL in PHP? - php

I try to show every result that the current username has in the database,
but it won't work..
I've tried anything and ya'll are my last hope.
Thanks in advance!
I can not get any answer from my code here below:
<?php
session_start();
include_once('../inc/db/config.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT serverip, servername FROM servers WHERE username=".$_SESSION['user_name']."";
$results = mysqli_query($mysqli, $query);
if(mysqli_num_rows($results) >= 1)
{
while($row = mysqli_fetch_array($results))
{
echo "<hr/>";
echo "<a href='../s_info.php?server='" . $row['serverip'] . "><h2>" . $row['servername'] . "</h2>";
}
}
?>

This line looks suspect to me:
$query = "SELECT serverip, servername FROM servers WHERE username=".$_SESSION['user_name']."";
Try:
$query = "SELECT serverip, servername FROM servers WHERE username='{$_SESSION['user_name']}'";
You should be able to echo out that string as a test and run it separately in mysql command line/phpMyAdmin or whatever tool allows you to test sql statements. Insure that it returns a result.

Related

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

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

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

Getting php variable to select statement not working

Here i am trying to pass the variable to php select query,but its not working.
couldn't figure out what is the problem.
code:
<?php
$cname = $_GET['c_name'];
include 'config.php';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM co_details where co_name="$cname"';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "<br>";
echo "Course Details <br>";
echo $row['co_name']."<br>";
echo $row['co_objectives']."<br>";
echo $row['co_outline']."<br>";
echo $row['co_prereq']."<br>";
echo $row['co_fee']."<br>";
echo $row['co_duration']."<br>";
}
mysqli_close($conn);
}
?>
what may be the reason?
Instead of variable $cname if i put the direct value then the query is executing successfully.
Note that single quoted strings like this one you have:
$sql = 'SELECT * FROM co_details where co_name="$cname"';
That variable that you think you have there will not get interpolated. It will only work by using double quoted strings.
$sql = "SELECT * FROM co_details where co_name='$cname'";
And as #Fred has said in the comments, stick with MySQLi including your connection error:
if(! $conn )
{
die('Could not connect: ' . mysql_error()); // mysql API doesn't belong
}
Change it to MySQLi interface:
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
And you should have used prepared statements instead as this is prone to SQL injection.
<?php
if(!empty($_GET['c_name'])) {
$cname = $_GET['c_name'];
include 'config.php';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
$sql = 'SELECT co_name, co_objectives, co_outline, co_prereq, co_fee, co_duration FROM co_details WHERE co_name = ?';
$select = $conn->prepare($sql);
$select->bind_param('s', $cname);
$select->execute();
$select->store_result();
$select->bind_result($co_name, $co_objectives, $co_outline, $co_prereq, $co_fee, $co_duration);
while($select->fetch()) {
echo "<br/>
Course Details: <br/>
$co_name <br/>
$co_objectives <br/>
$co_outline <br/>
$co_prereq <br/>
$co_fee <br/>
$co_duration <hr/>
";
}
}
?>
You can't use $cname directly in the string: try as shown below:
$sql = "SELECT * FROM co_details where co_name='".$cname."'";
Hope, it helps!
You are using single quote don't do like that change the query like this
$sql = "SELECT * FROM co_details where co_name='$cname'";

Connecting PHP to mySQL and retrieving data

i am new to PHP, and i am attempting to create a simple connection from html to mySQL using php. I met with some problems when running my codes.
this is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT username FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["userid"]. ;
}
} else {
echo "0 results";
}
$conn->close();
?>
after running on a browser, this is displayed:
connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT username FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "
id: ". $row["userid"]. ; } } else { echo "0 results"; } $conn->close(); ?>
Do you have mysql running on your localhost machine? You must verify that it is working first before you can connect via php. Also, make sure you have TCP/IP sockets open in mysql and to make sure it isn't just listening via unix sockets.
echo "<br> id: ". $row["userid"]. ;
this is a syntax error, no need to end it with a full stop.also the correct syntax to connect to sql server is
mysqli_connect("localhost","my_user","my_password","my_db") or die("");
Debug the code before posting it here.
maybe try testing it with a try catch statement. Its what I've done. this way you can display your error messages a little more nicely. As for the cause, PressingOnAlways is probably right
If you are using wampserver or any other server you need to put your php files into c:\wamp\www folder and run them in browser by typing localhost/nameofyourfile.php (change c:\wapm\www for your server installation path or type)
you have the syntax error in blow line
echo "<br> id: ". $row["userid"]. ;
. (dot) should not be there.
second you fetch usernamestrong text by following query
$sql = "SELECT username FROM users";
but you try to get userid
echo "<br> id: ". $row["userid"]. ;
try below code.
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT usersname FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["usersname"] ;
}
} else {
echo "0 results";
}
$conn->close();
?>

starting with mysql on an ubuntu server php

I am new to mysql but have recently tried doing some tutorials to advance my knowledge. Anyways I installed mysql on my ubuntu server as well as phpmyadmin. They both seem to work just fine, I created a database in phpmyadmin called "test" as well as a table called "teddy".
I put data into the table and I can clearly see it through phpmyadmin.
Now when I try accessing this database via a php script on my ubuntu server, nothing happens. Literally nothing. It reacts the same way as if I had a syntax error (a quick load with nothing displayed).
This is my code... If anyone knows where my mistake is it would be much appreciated.
Thank you
<?php
$username='root';
$password='***';
$database='test';
#$db= mysqli_connect('localhost', $username, $password, $database);
if (mysqli_connect_errno())
{
echo 'Error: Could not connect';
exit;
}
$query= "select * from test";
$result= $db->query($query);
$num_results= $result->num_rows;
echo $num_results;
?>
EDITED (based on drew 010)
Problem was the table was not called test but teddy so putting in this code worked.
"SELECT * FROM 'teddy'";
$db= new mysqli('localhost', $username, $password, $database);
if (mysqli_connect_errno())
{
echo 'Error: Could not connect';
exit;
}
$query = "SELECT * FROM 'teddy'";
$result = $db->query($query);
if ($result) {
$num_results = $result->num_rows;
echo $num_results;
} else {
echo "Query failed: {$db->error}\n";
}
?>
$result= $db->query($query); is probably returning false for some reason.
Try:
$query = "select * from teddy";
$result = $db->query($query);
if ($result) {
$num_results = $result->num_rows;
echo $num_results;
} else {
echo "Query failed: {$db->error}\n";
}
See http://www.php.net/manual/en/mysqli.query.php#refsect1-mysqli.query-returnvalues
I don't use mysql but I'm guessing because you're using mysqli_connect. Try mysql_connect instead
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
http://php.net/manual/en/function.mysql-connect.php
#$db= mysqli_connect('localhost', $username, $password, $database);
should be
$db= new mysqli('localhost', $username, $password, $database);

Categories