I added to a database a new table using PHPMyAdmin; when trying to access it from a PHP page I get the dreaded MySQL error "table doesn't exist".
Database connection data are OK, they are used a few lines above on the same page to access another table in the same database. If I do SHOW TABLES in PHPMyAdmin the new table is listed; if I do it from a PHP page the new table does not appear in the list.
Engine for the new table is MyISAM, like all other tables in the database. I can access the db server only via PHPMyAdmin.
Sorry, I forgot the code, here it is:
$db = mysql_connect ($db_host, $db_user, $db_password) or
die("Error message here");
$db_select = mysql_select_db($db_name, $db)or die("Error message here");
$query = ("SELECT * FROM `old_table`");
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
// do stuff - here it works
}
$query = ("SELECT * FROM `new_table`");
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
// do stuff - here it does not work
echo mysql_error();
}
On Unix, table names are case sensitive. On Windows, they are not. Fun, isn't it? Kinda like their respective file systems. Do you think it's a coincidence?
It probably depends on table type; MyISAM in your case.
Field names are case-insensitive regardless.
For database and table names, it depends on the underlying operating system. Identifier Case Sensitivity
The answer is simple: some typo or another silly mistake like this: you're connecting wrong server, editing wrong file or something of the kind. Just double check everything.
There is no particular error to cause this
The answer is: the table name or at least one of the field names is a reserved word.
To solve it, you can enclose the fields and table name with grave accents (`), e.g:
SELECT `value` FROM `pivot`;
Related
I'm working on a DB2 table on as/400. I'm trying to run a basic query against it but the table name contains a . in it. For example: my.table is the table name.
The problem is that PDO believes that I'm specifying a database name my with my table name table. Hence the prepared statement is failing and saying no such table table exists in database my. Changing the table name is not an option.
What is the best way to handle a period in the table name? I've tried escaping the period but haven't had any success.
Here's some example code of my problem:
$sql= "select * from '[THE.TABLE]'";
try {
$statement = $this->db->query($sql);
$results = $statement->execute();
foreach ($results as $result) {
print_r($result);
}
exit;
}
catch (\Exception $e)
{
//log issue and other stuff
}
The application is running in Zend Framework 2.
I stand corrected. As aynber mentioned in a comment, the solution was to use double quotes escaped correctly. The answer could be found in the question directed towards MySQL.
I am trying to get a result from the below piece of code, however, no result is being returned. $stmt->execute(array(id)) is not running as expected. It seems to work fine in other pieces of code, and I have compared them and don't see any differences.
$stmt = $mysql->dbh->prepare("SELECT * FROM keys WHERE type = ?");
if($stmt->execute(array($id))) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row["price"];
}
}
Thanks
keys is a MySQL reserved word
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Either you wrap it in backticks or use another name for it.
Just don't rename it to key. That too is a MySQL reserved word.
SELECT * FROM `keys`
Using error exception would have thrown you an error.
Add setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION) right after the connection is opened, if you're not already doing so.
Consult: http://php.net/manual/en/pdo.error-handling.php
Assuming you have already established a successful DB connection.
I have a series of websites, all of which must share the same information. Any updates to text must be made across all websites. Instead of editing each site individually and uploading the updates files one at a time, I figured it'd be far better to have a central source using MySQL - update the database, and all websites will be changed at once.
I have limited knowledge of PHP and MySQL - everything below is what I've been able to put together for myself so far, using various online sources:
<?php
//DB INFO///////////////////////////////////////////////////////////////////////////////////////
$host="localhost"; // Host name
$username="####"; // Mysql username
$password="####"; // Mysql password
$db_name="####"; // Database name
// Connect to server and select database
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get all the data from the "example" table
$pge_logbookabout = "SELECT * FROM pge_logbookabout";
$pge_logbookabout = mysql_query($pge_logbookabout) or die(mysql_error());
$row_pge_logbookabout = mysql_fetch_assoc($pge_logbookabout);
?>
So far, I can use the above to select a table and echo in the HTML using:
<?php echo $row_pge_logbookabout['rep_lbapr'];?>
That's cool, but I'm only able to select one single table using this - I'd like to be able to select ALL tables, and simply enter variables in where I need them.
Will I need to repeat the third section of the above code for each table, or is there a simpler way for me to do this?
To display all records in a table, you need to do:
while($row_pge_logbookabout = mysql_fetch_assoc($pge_logbookabout)){
echo $row_page_logbookabout['COLUMN'];
}
However if you mean that you want to display all records in each table, therefore you need separate queries to do so.
$query = mysql_query("select * from table1");
while($row_table1 = mysql_fetch_assoc($query)){
// code here
}
$query = mysql_query("select * from table2");
while($row_table2 = mysql_fetch_assoc($query)){
// code here
}
Please note this way of connecting to database, quering and fetching data will be deprecated starting PHP 5.5.0. Alternatively you can use PDO prepared statements
If you want to process over a series of tables you can use something like:
$query_tables = mysql_query('SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_name LIKE "%table%" ');
while($table = mysql_fetch_assoc($query_tables)){
$query = mysql_query("select * from ".$table['table_name'] );
// code here
}
You will have to make sure you choose the proper table names in the first query so you are processing the proper tables.
Then you can use php to loop over the tables updating a particular column/field. Not sure if that is what you are looking for...
More information at http://dev.mysql.com/doc/refman/5.0/en/information-schema.html
I agree with the above poster... switch to PDO_MYSQL.
Select multiple tables using mysql
Update mutiple tables using mysql
How are you hosting your websites? Are they on the same hosting? If that is the case, you can use localhost. Otherwise you will need to enter the external hosting mysql database credentials.(multisite single database setup).
First you select all tables, then you get the data from each one.
You could do this if you are using mysql_*, but I strongly recommend to use mysqli_* or PDO.
$result = mysql_query("show tables"); // Select all tables
while($table = mysql_fetch_array($result)) {
$queryT = mysql_query("select * from '".$table[0]."'");
while($rtable = mysql_fetch_array($queryT)){
// data of the table
}
}
Alright, so I'm fairly new to PHP and SQL/MySQL so any help is appreciated.
I feel like I took the right approach. I searched php.net for "MySQL show all table names", it returned a deprecated method and suggested using a MySQL query on SHOW TABLES [FROM db_name] [LIKE 'pattern'] I'm not sure what "pattern" means but, I searched for "SQL Wildcard" and got the "%" symbol. According to everything I found, this should work and output the table names at the end, but it does not. Any suggestions? Thanks in advance.
<?php
if ($_REQUEST["username"]=="coke"&&$_REQUEST["password"]=="pepsi"){
echo 'You have successfully logged in.';
echo '<br />';
echo 'These are your tables:';
echo '<br />';
$link = mysql_connect("sql2.njit.edu", "username", "password");
mysql_select_db("db_name") or die(mysql_error());
$result = mysql_query('SHOW TABLES [FROM db_name] [LIKE '%']');
echo $result;
}
else
echo 'You did not provide the proper authentication';
?>
I get no errors. The output is exactly what's echoed, but no table names.
The square brackets in your code are used in the mysql documentation to indicate groups of optional parameters. They should not be in the actual query.
The only command you actually need is:
show tables;
If you want tables from a specific database, let's say the database "books", then it would be
show tables from books;
You only need the LIKE part if you want to find tables whose names match a certain pattern. e.g.,
show tables from books like '%book%';
would show you the names of tables that have "book" somewhere in the name.
Furthermore, just running the "show tables" query will not produce any output that you can see. SQL answers the query and then passes it to PHP, but you need to tell PHP to echo it to the page.
Since it sounds like you're very new to SQL, I'd recommend running the mysql client from the command line (or using phpmyadmin, if it's installed on your system). That way you can see the results of various queries without having to go through PHP's functions for sending queries and receiving results.
If you have to use PHP, here's a very simple demonstration. Try this code after connecting to your database:
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result
echo($table[0] . "<BR>"); // print the table that was returned on that row.
}
For people that are using PDO statements
$query = $db->prepare('show tables');
$query->execute();
while($rows = $query->fetch(PDO::FETCH_ASSOC)){
var_dump($rows);
}
SHOW TABLES
will show all the tables in your db. If you want to filter the names you use LIKE and wildcard %
SHOW TABLES FROM my_database LIKE '%user%'
will give you all tables that's name include 'user', for example
users
user_pictures
mac_users
etc.
The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.
It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.
Queries should look like :
SHOW TABLES
SHOW TABLES FROM mydatabase
SHOW TABLES FROM mydatabase LIKE "tab%"
Things from the MySQL documentation in square brackets [] are optional.
you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.
Sure you can query your Database with SHOW TABLES and then loop through all the records but that is extra code lines and work.
PHP has a built in function to list all tables into an array for you :
mysql_list_tables - you can find more information about it at The PHP API page
//list_tables means database all table
$tables = $this->db->list_tables();
foreach ($tables as $table)
{
echo $table;
}
Am a newbie in PHP and MySQL, how can I create a database with a phone number being the database name? The phone number is in the format of +256720742675. I have tried the code below but keeps on trowing an error.
<?php
$database= $_POST[PhoneNumberTextBox];
//check for MySQL server connection
$connection = mysql_connect("localhost","root","");
if (!$connection)
{
die('Could not connect to database: ' . mysql_error());
}
//Create database
$sql= "CREATE DATABASE $database";
if(!mysql_query($sql,$connection))
{
die('Could not create database'.mysql_error());
}
else
echo"Database Created<br\>";
//Close connection
mysql_close($connection);
?>
don't know where to begin... From:
You should not use root database user in your php file or,
You should not create databases from your _POST requests
I can see so many bad things happening...
First of all it doesnt sound right to create a table for each number.
Starting a database name with a number is not allowed. If you insist though, try prepending a letter to it.
For Example: N256720742675
The answer is to store telephone numbers in a field. Not create a new database per telephone number:
Create a table like this:
create table phonenumbers (
phone varchar(20) not null primary key,
related_field1
......
related_field25
Now you can use code like this:
$conn = mysql_connect("localhost","named_user","long_password_with_entropy");
$phone = mysql_real_escape_string($_POST['PhoneNumberTextBox']);
$sql = "INSERT INTO phonenumbers (phone, field1, field2, field3)
VALUES ('$phone','1','2','3') ";
//The quotes ^ ^ are essential !
Now you're storing stuff in a database in a way that enables them to be retrieved.
And you can select all your data per phonenumber like this:
SELECT p.*, c.*
FROM phonenumbers p
LEFT JOIN calls c ON (c.phonenumber = p.phone)
WHERE p.phone = '$phone';
Hard rules
Set a strong password on your user account.
Don't log in with root.
Escape all $_* super globals using mysql_real_escape_string. (Or even better: use PDO).
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
See this tutorial about mysql and php: http://www.tizag.com/mysqlTutorial/
It's one of the few that get this topic right.