Why won't this php SELECT FROM query work? - php

Here is my simple php code:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "********"; //hiding my password
$dbname = "course";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM tutors";
$result = $conn->query($sql);
if( $result === true ) {
echo "good";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
while($row = $result->fetch_assoc()) {
echo $row["name"];
}
?>
</body>
</html>
In my database called "course", I have a table called "tutors" which has a column called "name". I have two entries in that table with the names "deep thought" and "pyrenees" respectively.
When this code runs however, the only thing that prints out is:
Error: SELECT name FROM tutors
It is supposed to simply print out the two names that I mentioned before.
Does anyone know why this happens? I know for a fact that I have the two entries in my table!

I think the word "name" is a MySQL reserved word. Wrap your query variables in a tilde backticks like this:
$sql = "SELECT `name` FROM `tutors`";
This helps to escape those values from MySQL thinking you're trying to referencing a built in variable.

Why not use mysqli like so:
function getFollowers($link, $userid)
{
$sql = "SELECT users.id, username, profileImg FROM following INNER JOIN users ON users.id = following.userid WHERE followid = " . $userid;
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
$resultsArray[] = $row;
}
mysqli_free_result($result);
return $resultsArray;
}
This is just a clean example, I am sure you get the idea.
Here is what $link is
function connection()
{
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
return $link;
}
Or without the methods:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT name FROM tutors";
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
echo $row["name"];
}
mysqli_free_result($result);
To check if the query was successful you can do this:
if (mysqli_num_rows($result) > 0)
{
//has rows, so whatever you want with them.
}
You put the condition after defining $result.

Related

PHP and mysql connection not working

I have written following code to connect mysql in php but I am not getting output.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if ($mysql_conn->connect_error) {
die("Connection failed: ". $mysql_conn->connect_error);
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysql_select_db('yieldofvanillin', $mysql_conn);
if (!$db_selected){
die ('Can\'t use : ' . mysql_error());
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = $mysql_query($query);
while ($line = myql_fetch_array($result, MYSQL_ASSOC)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysql_close($mysql_conn);
?>
The database name is "yieldofvanillin" and it has five column. I an getting output Connected successfully. After that no output. Please let me know the bug in code.
i have remove errors. which i mention in comments. Code Reference PHP Manual. you should read this manual (strongly recommended)
<?php
$mysqli = new mysqli("localhost", "root", "pravin", "yieldofvanillin");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
echo $row["products"];
echo $row["Microorganism"];
echo $row["yield"];
echo $row["Reference"];
}
/* free result set */
$result->free();
}
you're mixing mysqli and mysql libraries.
the code should be:
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if (mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_error());
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysqli_select_db($mysql_conn,'yieldofvanillin');
if (!$db_selected){
die ('Can\'t use : ' . mysqli_error($mysql_conn));
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = mysqli_query( $mysql_conn,$query);
while ($line = mysqli_fetch_assoc($result)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysqli_close($mysql_conn);
?>
Remove error in your code.Read carefully php manual.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$db = "yieldofvanillin";
// Create connection
$mysqli = new mysqli($servername, $username, $password, $db);
/* connection string*/
if ($mysqli->connect_errno) {
die("Connection failed: " . $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
}
$result->free();
}
$mysqli->close();
?>
Your output not showing because mysql_fetch_array is not correct.Because you are mixing mysql_ and mysqli_ functions and you called myql_fetch_array that doesn't exist in mysqli. MySQL and MySQLi are two different PHP extensions and they cannot be mixed. Because the former is deprecated in mysqli

Need help to display data from mysql database

I would need some help with showing data that I have on my database but I can't seen to be able to.`
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$connect = mysqli_connect($servername, $username, $password, $dbname) or die ("connection failed");
//Query
$query = "SELECT * FROM 'Students'";
mysqli_master_query($dbname, $query) or die ("Error while Query");
$result = mysqli_master_query($dbname, $query);
$row = mysql_fetch_array($result);
while ($row = mysql_fetch_array($result)) {
echo "<p>".$row['Name']."</p>";
};
mysql_close($connect);
?>`
I am pretty new to this so I could have missed something simple. Any help appreciated.
Below is a sample code of the normal procedure to connect to a database and to select data from it. Please follow this type of coding since MySQL is now deprecated and MySQLi is used.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
For further reference check out http://php.net/manual/en/book.mysqli.php and also https://www.w3schools.com/php/php_mysql_insert.asp

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

is it possible select Database 2 simultaneously in the same conection

I have problem with 2 select Databases from the same connection simultaneously, the code is:
#$dbmssSQLGestasa_conn = mssql_connect($servidor, $usuario, $contra);
if(!$dbmssSQLGestasa_conn){
header("Location:nobase.php");
exit();
}
mssql_select_db('GESTASA', $dbmssSQLGestasa_conn);
the code of the other connection:
#$dbmssSQLTasa_conn = mssql_connect($servidor, $usuario, $contra);
if(!$dbmssSQLTasa_conn){
header("Location:nobase.php");
exit();
}
//Apertura de la base de datos
mssql_select_db('TASA', $dbmssSQLTasa_conn);
it dont work and give me error "(severity 16)".
is It possible do 2 or more selections databases en la same connection mssql?
Dont use mysql_select_db();
In Mysqli :
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM test123.posts"; // databse.tablename
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mack[] = $row;
}
}
$sql1 = "SELECT * FROM portal.abouts"; // databse.tablename
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
$mack1[] = $row1;
}
}
echo "<pre>";
print_r($mack);
print_r($mack1);
echo "</pre>";
$conn->close();
You can easily use 2 databases in same time with Below Codes
I'm Using variables as Capital word But you can use your own variable words.
<?php
define('HOST', "YOURHOSTNAME");
define('USER', "YOURHOSTNAME");
define('PASS', "YOURHOSTNAME");
define('DATABASE1', "NAMEOFDATABASE1");
define('DATABASE2', "NAMEOFDATABASE2");
$DATABASE1 = mysqli_connect(HOST, USER, PASS, DATABASE1);
$DATABASE2 = mysqli_connect(HOST, USER, PASS, DATABASE2);
if(!$DATABASE1){
die("DATABASE1 CONNECTION ERROR: ".mysqli_connect_error());
}
if(!$DATABASE2){
die("DATABASE2 CONNECTION ERROR: ".mysqli_connect_error());
}
$sql = "SELECT * FROM TABLE"; /* You can use your own query */
$DATABASE1_QUERY = mysqli_query($DATABASE1, $sql);
$DATABASE2_QUERY = mysqli_query($DATABASE2, $sql);
$DATABASE1_RESULT = mysqli_fetch_assoc($DATABASE1_QUERY);
$DATABASE2_RESULT = mysqli_fetch_assoc($DATABASE2_QUERY);
/* SHOW YOUR RESULT HERE WHICH DATABASE YOU WANT FROM */
echo $DATABASE1_RESULT['id'];
echo $DATABASE2_RESULT['id'];
/*After complete your all work don't forgot about close database connections*/
mysqli_close($DATABASE1);
mysqli_close($DATABASE2);
?>

MySqli Select is not working

I couldn't figure out why it has some problem like this. The error displayed mysqli_fetch_assoc() expects parameter 1 to be mysqli_result.
My code is like this. I don't know which one is wrong.
Have a look at my con.php.
<?php
$conn = mysqli_connect('localhost', 'username', 'password');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
and this is my page.php
<?php
include 'con.php';
$link = mysqli_connect('localhost', 'username', 'password', 'username') or die("Error " . mysqli_error($link));
$query = " SELECT thread_id, thread_name, thread_date
FROM forum_thread
ORDER BY thread_date";
$result = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($result)) {
$thread_id = $row ['thread_id'];
$thread_name = $row['thread_name'];
$thread_date = $row['thread_date'];
echo "$thread_id, $thread_name, $thread_date";
Any ideas? Appreciate any answers from you. Cheers!
I think I figured it out:
Change $result = mysqli_query($link,$query);
to $result = mysqli_query($conn,$query); since $conn is your DB connection, not $link
as per what you posted above
<?php
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
and remove:
$link = mysqli_connect('localhost', 'username', 'password', 'username') or die("Error " . mysqli_error($link));
since you're already loading your DB con with include 'con.php';
Or this way:
<?php
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name') or die("Error " . mysqli_error($conn));
$query = " SELECT thread_id, thread_name, thread_date
FROM forum_thread
ORDER BY thread_date";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result)) {
$thread_id = $row ['thread_id'];
$thread_name = $row['thread_name'];
$thread_date = $row['thread_date'];
echo "$thread_id, $thread_name, $thread_date";
The error message indicates the query did fail for some reason. Instead of just using $result test to see if it's valid and if not output the error to the screen or a log file:
if ($result) {
// continue processing $result
}
else {
echo mysqli_error($link);
}
Edit:
The 4th parameter in the mysqli_connect should be the name of the database, "abc" or whatever.
Try to use following code
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli- >connect_error;
}
Here when you try to get connection object itself you can identify the problem if something goes wrong.

Categories