MySQLi how to check if table exists? [duplicate] - php

This question already has answers here:
MySQLi Table Exists
(5 answers)
Closed 3 years ago.
I want to create table by app if there's no such table. But doing it for the first time... Need some help, tho
//connecting...
$mysqli = new mysqli($db_params['host'], $db_params['login'], $db_params['pass'], $db_params['name']);
if ($mysqli->query("SHOW TABLES LIKE `products`")){
echo ' YES';
} else echo 'no';
It always says NO.

Read their documentation? https://dev.mysql.com/doc/refman/5.5/en/replication-features-create-if-not-exists.html Seems like you can do that easily:
CREATE TABLE IF NOT EXISTS `products`
This way you don't have to check first whether a table exists or not, you just create one if it doesn't.
And it seems like you have a syntax error, which is probably the reason why your code keeps returning "no". This should work:
SHOW TABLES LIKE 'products';
Just use single or double quotes, no backticks like `.
You use backticks (`) for table and column names, single (') or double quotes (") for strings, in this case you are giving a string so you should use single or double quotes.

In order to create a table if it not exists, you can use
CREATE TABLE IF NOT EXISTS

Use PHP DESCRIBE statement.
if(mysql_query("DESCRIBE `table_name`")) {
// Exists
}

This solution works for me JUST FINE:
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// SQL query
$sql = "SHOW TABLES IN `tests`";
// perform the query and store the result
$result = $conn->query($sql);
// if the $result not False, and contains at least one row
if($result !== false) {
// if at least one table in result
if($result->num_rows > 0) {
// traverse the $result and output the name of the table(s)
while($row = $result->fetch_assoc()) {
echo '<br />'. $row['Tables_in_tests'];
}
}
else echo 'There is no table in "tests"';
}
else echo 'Unable to check the "tests", error - '. $conn->error;
$conn->close();
?>
For a complete and more examples, here the source : http://coursesweb.net/php-mysql/check-table-exists-database_t

Related

Selecting * from table returns nothing

I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!

php mysql cant find id if there is letters inside [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
When i try to search for a available id with numbers, it echos correctly.
HOWEVER, if there is a single letter inside, like this: 5325252T, It wont find it in the database.
I have a column with type: longtext
How can I get around this? I never noticed this problem before and now I'm in a hurry to fix it...
Btw, If i echo all the tables for rusp_9_cf7dbplugin_submits, it also shows those ids with letters inside. Really weird.
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT field_value FROM rusp_9_cf7dbplugin_submits WHERE field_value = 5325252T"; // If i remove the T, It will find the id and echo it in a table, but if the T is there, it wont find the id at all...
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["field_value"]."</td><td>".$row["field_value"]." ".$row["field_value"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Just enclose the field_value value in single inverted commas ' since adding a character makes the SQL engine interpret that value as a number where as it is a string literal, whereas if its just numbers then it interprets it as an integer.
Your code becomes...
...
$sql = "SELECT field_value FROM rusp_9_cf7dbplugin_submits WHERE field_value = '5325252T'"; // If i remove the T, It will find the id and echo it in a table, but if the T is there, it wont find the id at all...
...

Creating a mysql database with "." in the name (using php) [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've been having some trouble recently with trying to automate new database creations with a php script.
Basically, the script takes the new login username and creates a database (and then insert some tables and data later on, which is also done via a php script).
I used to have to manually create the database, but now need to make it automated.
The issue is that I used to be able to just create a new database using the phpadmin "new database" function from the web GUI and put in names like "test1.siteA", "userb.siteB".
However, now that I've tried to do the same via php script, it keeps giving me the "You have an error in your syntax..." from my last "echo".
Main parameters are:
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
I've found that the error would disappear once I remove the .site part from the code (it still exist even if I combine the $dbname into 1 line).
According to some articles that I've found online, it seems that MySQL doesn't allow special characters like "." to be included in the database name.
It just seems very weird to me that the ".site" can be added manually through phpMyadmin while the php/mysqli script doesn't allow this.
The full script is as follows (I'm sure it can be heavily improved, so any suggestions regarding that are also welcome):
<?php
define("_VALID_PHP", true);
require_once(APPPATH. "/libraries/init.php");
include (BASEPATH . "/database/DB_temp.php");
$row = $user->getUserData();
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
// Create connection
$conn = mysqli_connect($servernm, $usnm, $pasd);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check if DB exist
$sql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
$check = mysqli_query($conn,$sql)
or die("Connection failed: " . mysqli_connect_error());
while($row = mysqli_fetch_array($check,MYSQLI_NUM))
{
$dbval = $row[0];
}
if ($dbval == "0")
{
$createsql = "CREATE DATABASE '$dbname' ";
}
if ($dbval == "1")
{
$createsql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
}
if (mysqli_query($conn, $createsql)) {
Echo "Completed. DBVAL= " .$dbval ;
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
?>
PHP version: 5.6.18
phpmyadmin: 4.5.4.1
Ubuntu 14.04
Apologies if I've made some posting errors on here. Do let me know about them and I'll try to correct it as much as I can. Any help is greatly appreciated!
. is a meta character in SQL, use to separate db/table/field names:
SELECT foo.bar.baz FROM sometable
^---------- database 'foo'
^------- table 'bar'
^--- field 'baz'
You should NOT be using metacharacters in any identifiers. It just leads to pain later on, and having to do stuff like:
SELECT `foo.bar`.baz.qux FROM ...
^^^^^^^^^--------- database 'foo.bar'
^------ table 'baz'
^-- field 'qux'
So you can use backticks if you absolutely have to, but you shouldn't be doing this in the first place.
try wrapping the database name with back ticks.
$dbname .= '`.site`';

Sql echo row with php [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I can connect to DB but i cant echo , all time that said 0 results but my DB have TABLE (text) with 2 COLUMN id and text and i have inserted text in my table.
$con = mysqli_connect("localhost","1078362","nenaddurmisi022");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT vesti FROM comment";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["vesti"]."<br>";
}
}
else {
echo "0 results";
}
mysqli_close($con);
You're using all mysqli functions except for your database connection. Try changing the first line to...
$con = mysqli_connect("localhost", "1078362", "nenaddurmisi022");
...and change the last line to...
mysqli_close($con);
I'm guessing there are a lot of errors generated by this script, but you're not seeing them. You should add these lines to the top of the script...
error_reporting(E_ALL);
ini_set('display_errors', 1);
try
$sql = "SELECT * FROM text";
instead of
$sql = "SELECT text FROM text";
also be sure you'r table name is text.
one last thing you could try is to replace
echo $row["text"]."<br>";
by
print_r($row);
to see if there's a result set from you'r Database

SQL insert not saving to database [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
Im having trouble getting this simple code to work, it,s part of a rating script for a product page.
$connn = new mysqli($servername, $username, $password, $dbname);
if ($connn->connect_error) {
die("Connection failed: " . $connn->connect_error);
}
$vresult1 = mysqli_query($connn,"SELECT * FROM rating_log WHERE ip=$userIP AND product_id=$pid");
if ($vresult1->num_rows > 0) {
// ERROR: user already voted
$v_msg = '<div style="color:red;">You have already voted on this product!</div>';
} else {
// enter vote
mysqli_query($connn,"UPDATE wc_products SET rating=$votecnt1");
mysqli_query($connn,"INSERT INTO rating_log (ip, product_id) VALUES ($userIP, $pid)");
$v_msg = '<div style="color:green;">Thank you for voting! DEBUG['.$userIP.'-'.$pid.']</div>';
}
$conn->close();
} // end rating
All this should do is add a new entry which logs a user ip and the id of the product, then update the product db to register the vote. The update works fine but it wont log the user.
Try this:
$userIP = $mysqli->real_escape_string($userIP);
$pid = $mysqli->real_escape_string($pid);
mysqli_query($connn,"INSERT INTO rating_log (ip, product_id) VALUES ('$userIP', '$pid')");
Single quotes should be used for string values like in the VALUES() list. for more details read this post answer:
When to use single quotes, double quotes, and backticks in MySQL

Categories