Table does not exist, but it EXISTS - php

So I'm starting to learn how to use PHP to access MYSQL databases and after successfully connecting to the database. I want to select data from it. However I get the issue that the table doesn't exist. Yet, it exists when I check it in my phpmyadmin. I've checked spelling, capitalization, etc.. and nothing works. I've tried it with multiple databases and I get the same error. So I'm really confused as to whats going on because from the looks of it, there is NOTHING wrong with the code. I've tried running the SQL query in phpmyadmin just to verify that the query works.. and it does. I just get the error "Table 'test.blog_table' doesn't exist" with the code below
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_in_use = "test";
$conn = new mysqli($host, $user, $password, $database_in_use);
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
echo $conn->host_info . "<br>";
$sql = "SELECT * FROM blog_table";
$result = $conn->query($sql);
$result = $conn->query($sql) or die($conn->error);
$conn->close();
?>
So I'm just completely lost and have no idea whats going on with it.

Solved! I connected to the wrong database, which is why the tables were there, but weren't showing up. Since I was connecting to a different database and the one I created tables in didn't have the default port.

Probably you are missing the mysqli and the mysqlnd PHP extensions.
Also, I recommend you to use \PDO object to fetch queries to your DB instead of the mysqli driver, if you do it, you will be free to change in the future to a PostgreSQL DB for example anytime just changing the DSN in the constructor (you need for that the PDO and the pdo_whatever_db_driver (e-g.: pdo_mysql) extensions.

Related

How can I connect from a website to a Microsoft SQL Database using PHP

Ive worked with the typical PHPMyAdmin interface until now when it comes to databases.
Now Ive been handed a .bak file and pointed to "Microsoft SQL Server Managment Studio" and told to use that.
My problem is that I dont know how to do the most basic things. For instance when I want to connect to a PHPMyAdmin Database I know that I need to define the host, the user, the password and the database and throw that information into a mysqli_connect() and thats that.
So my question is:
How do I connect to my database that I have in my SQL Server Managment Studio? The same way I did before? And if so where do I find the needed information like host, user, password?
I would install the SQLSRV PDO extension. Then use a similar methodology to access the database
$database = "";
$server = "";
$conn = new PDO( "sqlsrv:server=$server ; Database = $database", DB_USER, DB_PASSWORD);
$sql = "SELECT * FROM Table WHERE MemberID =:MemberID";
$iMemberID = 5;
$st = $conn->prepare($sql);
//named placeholders within the execute() as an array.
$st->execute(array(':MemberID'=>$iMemberID));
//OR using bind param..
$st->bindParam(':MemberID', $iMemberID);
while ($row = $st->fetch()){
echo "<pre>";
var_dump($row);
echo "</pre>";
}

Why does my mysqli_query return false?

I realise there are a lot of questions like this here, but none of them seem to help me. The problem is as follows:
I have a website with an SQL Database, and now I am developing an application that reads the data. I've read that the best way to do that is a web service, so I'm in the process of writing one now. First, I'm trying to get all the data to display on a webpage, for testing purposes. I have the following code now:
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$db = "mydatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $db, 3306);
// Check connection
if (!$conn){echo "Not connected";} else {echo "connected";}
$query = "SHOW TABLES FROM mydata";
$result = mysqli_query($query) or die(" but not executed" . mysqli_error());
?>
When I save this and go to mywebsite/test.php, it displays the following:
connected but not executed. That means that it connects right, but the mysqli_query() returns false. However, mysqli_error is empty.
This is the entire test.php file. Am I missing something?
"Am I missing something?"
Yes, db connection arguments to both mysqli_query() and mysqli_error().
RTM's
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
It's all in there.
Btw, this is a community wiki. No rep should come of this.
If that still doesn't work, then you may have to remove the port , 3306.
Your $query appears to say
SHOW TABLES FROM mydata
However, your database is actually called mydatabase, as demonstrated on the $db line.

PHP: could not find database

i am having difficulty with connecting my database to mysql, i have tried many different ways of trying to get it to connect to my database, but none these methods seem to work. I am only new to php and i could be missing something, but i dont know what it is.
This is for a search engine, i have the form created.
I would think that my problem is coming from this line of code, mysql_connect("localhost", "root", "") or die("could not connect");?!
I was wondering if i could be told what is the problem and how to fix it, thank you so much.
here is my code below.
<?php
//connect
mysql_connect("localhost", "root", "") or die("could not connect");
mysql_select_db("search") or die("could not find database");
$output = '';
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","", $searchq);
$query = mysql_query("SELECT * FROM gp management system WHERE Title LIKE '%$searchq%' OR Description LIKE '%$searchq%' OR Keyword LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
}
else{
while($row = mysql_fetch_array($query)) {
$Title = $row['Title'];
$Description = $row['Description'];
$Keyword = $row['Keyword'];
$output .= '<div> ' .$Keyword. ' </div> ';
}
}
}
?>
SQL errors:
SELECT * FROM gp management system WHERE Title...
^^-- table name
^^^^^^^^^^ aliasing 'gp' as 'management'
^^^^^^-- extra unknown garbage
Table names shouldn't have spaces to begin with, but if you insist on having them, then you need proper quoting:
SELECT * FROM `gp management system` etc...
^--------------------^
Never output a fixed/useless "could not search" error. Have the DB tell you what went wrong:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^^
As your only new, you really should stop using mysql_ and change to mysqli_ or (my preference) PDO(). Your message in your title seems to be coming from your selectdb line, so you're actually connecting to the database fine, it's just not able to locate the schema that you are trying to use (i.e. "search" does not exist as a schema name in your DB environment). Unless that's not the error that you are getting, in which case it's a flaw in your actual SQL query. Without an accurate statement of what you are getting back on the screen when you try to run the script then not much can be done to help.
I would rather do somehow like I did ages ago, see below:
function db_connect($host, $username, $passwd, $db_name) {
$db = mysql_connect($host, $username, $passwd);
if (!$db) {
echo "Login to database failed: ";
echo mysql_error();
return false;
}
$result=mysql_select_db($db_name); //Select the database
if (!$result) {
echo "Cannot find the database: ".$db_name;
echo mysql_error();
return false;
}
return $db; //Database descriptor
}
However you shouldnt rely on the old MYSQL extension, but use MYSQLi.
EDIT: as #tadman pointed out there were a # sign infront the mysql_connect call, however there is an if statement for checking and a call to error output.
As others have said, your code is something of a mess - you seem to be new to programming, not just in PHP. But everyone has to start somewhere, so....
You might want to start by learning a bit about how to ask questions - specifically you have included a lot of code which is not relevant to the problem you are asking about - which is about connecting to MySQL. OTOH you have omitted lots of important information like the operating system this is running on and what diagnostics you have attempted. See here for a better (though far from exemplary example).
Do read your question carefully - the title implies an issue with mysql_select_db() while in the body of the content you say you think the problerm is with mysql_connect(). If you had provided the actual output of the script we would have been able to tell for ourselves.
You should be checking that MySQL is actually running - how you do that depends on your OS. You should try connecting using a different client (the mysql command line client, sqldeveloper, Tora, PHPMyAdmin....there are lots to choose from).
You should also check (again this is operating system specific) that your MySQL instance is running on the same port as is configured in your php.ini (or overridden in your mysql_connect() call).
MySQL treats 'localhost' as something different from 127.0.0.1 on Unix/Linux systems. If this applies to you try 127.0.0.1 in place of localhost.
or die("could not connect");
Does not help in diagnosing the problem. If instead you...
or die(mysql_error());
You will get a more meaningful response.
BTW: while writing code using the mysql extension rather than mysqli or PDO is forgivable, I am somewhat alarmed to see what appears to be medical information managed with no real security.

PHP/MYSQLI: mysqli_query fails in PHP

First off, I'm a total noob in mysql(i) language and know a little more than the basics of PHP.
Note: I do not manage or own / have access to the server on which the webpage currently is hosted. I can however access the phpMyAdmin page.
That said, I've got a webpage on which I am trying out some stuff. Right now I'm trying to make a log-in page linked to a database.
Now, behold the code:
$mysql_host = "localhost";
$mysql_user = "my_user";
$mysql_database = "my_database";
$mysql_password = "my_password";
$table = "my_tablename";
// Create connection
$con=mysqli_connect($mysql_host,$mysql_user,$mysql_password,$mysql_database);
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// sending query
$result = mysqli_query("SELECT * FROM my_tablename");
if (!$result) {
echo "Query to show fields from table failed! :-(";
}
Now, here comes the actual problem. As soon as I launch the page it will give me my "Query to show fields from table failed!" error message. But when I enter the same query on the phpMyAdmin 'SQL' tab, I get the wanted results. How come the webpage gives me an error, while the phpMyAdmin gives me the results, and, how do I solve it?
Use correct syntax:
$result = mysqli_query($con, "SELECT * FROM my_tablename");
You forgot to link current mysqli connection. First parameter is link - which mysqli connection you want to use (good for multiple conns) and then the second is your query.

MySQL I can not write data into the database

Hello guys i have problem with inserting data in mysql database.I accepted a project that my friend worked.
I make simple php test file and try to insert in table _content_city. query is successfully executed bu no records in database column when i check in phpmyadmin.
$handler = mysql_connect($server, $user, $pass);
$database = mysql_select_db($dbname);
if(!$handler) :
die("Faild connect to MySQL :" . mysql_error());
endif;
if(!$database) :
die("DB with name ". $dbname . " no exists " . mysql_error());
endif;
mysql_query("INSERT INTO _content_grad (wishlist) VALUES('BlaBlaBla') ") or die(mysql_error());
printf ("Inserterd records: %d\n", mysql_affected_rows());
When i execute this code in browser i have message Inserterd records: 1
But when i check in phpmyadmin that data no exist in column. I dont know whay.
You guys can see image and u will see column wishlist is empty.
http://img710.imageshack.us/img710/1852/5hfw.png
I check foreign_keys and remove all foreign_keys and again dont work.
Like test i make new database with name new_test_base and make table albums and column title and like test i execute my php code and all data is successfully inserted when i check in phpmyadmin. So problem is only in that database, i have full access and privilegies i use root (ALL)
Any solution to fix this. Thanks
The MySQL_* range of functions have been depreciated and are no longer reccomened for use. Use the MySQLi_* range of functions instead.
In your code, put the following line echo mysql_errno($handler) and it should display the latest error retuned by MySQL, a MySQLi version of this function is also available.

Categories