This question already has answers here:
How to check if mysql database exists
(23 answers)
Closed 8 years ago.
$pdo_mysql = new PDO("mysql:host=localhost", "ales", "alespass");
$result = $pdo_mysql->query("SHOW DATABASES LIKE `dbname`");
if ($result) { //not work.
print "no";
} else {
print "yes";
}
You can not use CREATE DATABASE IF NOT EXISTS or new PDO("mysql:host=localhost;db=dbname" ...
You have a typo error in your comment on #robin s answer, I think the condition should be if (!empty($result)) with that exclamation mark. It is printing not exists because $result is not empty when database exists. Therefore using this $result = $pdo_mysql->query("SHOW DATABASES LIKE '" . DB_NAME . "'"); if (!empty($result)) { print "exists"; } else { print "no exists"; } should work. I hope that helps
Manual:
PDO::query() returns a PDOStatement object, or FALSE on failure.
Your query is valid and should never fail (ignoring possible lower level issues).
$result will always evaluate to TRUE-ish, so the flow will always enter the if ($result) block.
(if (empty($result)) makes little to no sense)
You need to check whether the query returns zero row (zero result is not an error).
On second thought:
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
It is safer to do something like this:
if ($result->fetch() === FALSE) {
// result set is empty
}
CREATE DATABASE IF NOT EXISTS
should do the trick. If it doesn't, check for the existence first via
SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'dbname'
it will return you the database name itself, so you can check if the count of the query is > 0, the result is != 0...and so on. However you like.
The problem with your queries is the wrong use of backticks, you need to use single quotes, not backticks.
' instead of `
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I an trying to query a mySQL database using a PHP function. Intermittantly, the function that I am using does not seem to return a result. As far as I can detect, it's not a null response, and based on the function, it doesn't seem to be returning an invalid result ( the return string Nuthin in this case ).
function GeneratePiece2 ($sqlstr){
$conn = new mysqli(gHOST, gUSER, gPASSWORD, gDATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sqlstr);
$returnable = "";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row;
$returnable = $row;
}
} else {
return "nuthin";
}
$conn->close();
return $returnable;
}
I've been using the same SQL Query of
SELECT Name FROM Char_Name_full WHERE Male=1 AND DivisionID=12 ORDER BY RAND() LIMIT 1
Around 80% of the time I will receive a result of something like {"Name":"Christoph"} but 1 out of 10 returns nothing.
If someone is having problems with fetch_assoc() returning "Undefined index":
Check the indexes names (database Column name) - they are case sensitive.
Example:
For "SELECT Name FROM..." Your code must be $row["Name"]. Not NAME or name.
In your query, you are checking if the number of rows is greater than zero, but you are not doing anything to check if the value that is returned is Null. The behaviour that you are describing matches the scenario of at least 1 row in 'Name' that has a NULL value.
Note that I am not going to comment on your code structure or syntax here, but I have changed your response values to help identify / prove that a null value is the issue here.
Also, if your query is limited to a single row, then the while loop will only iterate once.
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Echo out the values for Name in the result set
if(is_null($row["Name"], ))
echo '[NULL]';
else
echo $row["Name"];
// your application logic ;)
$returnable = $row;
}
} else {
return "no rows";
}
Please consider using a SQL IDE like Toad for MySQL along side your development, then you can visually inspect your data for these issues without writing code hacks :)
I have the following code in my CRUD class
//function to execute prepared statement query
//$sql = select , insert, update and or delete query => insert into table(col,col,col,...col) values(?,?,?,...?);
//$dataTypes = "ssidb", it could be any char in s=>string, i=>integer, d=>double and b=>blob data
//$param = $val1,$val2,$val3,....$valn, this is an option coma separated values to bind with query
public function dbQuery($sql,$dataTypes="",$param=""){
try{
$this->connect();
$stmt = $this->con->stmt_init();
$stmt = $this->con->prepare($sql);
$stmt->bind_param($dataTypes, $param);
if($stmt->execute() === true){
return true;
}
else{
return false;
}
}catch(Exception $e){
$this->errorMsg = $e->getMessage();
}
$this->closeConnection();
}
I am calling this method from my index page like this:
if(isset($_POST['btnSearch'])){
//search for some record with primary key
$sno = intval($_POST['sno']);
$sql = "SELECT sno,std_name,email,roll_number FROM table_1 WHERE sno = ?";
$dTypes = "i";
$params = $sno;
if($db->dbQuery($sql,$dTypes,$params)){
echo('Record exists');
}
else{
echo('Record did not found'.$db->errorMsg);
}
}//search for record
//inserting values to table_1 table
This always return true either there is any record exists or not?
Whats going wrong with this code?
There are many flaws in your code, and it will never work as intended, even after fixing this particular problem.
Before starting with a class, you need to practice heavily with raw API functions, and learn how to use them by heart. Otherwise your class will be just a straw house that will crumble from a softest touch.
Now to your problem.
To solve it, you need to understand one very important mathematical conception, that reads "empty result is not an error". 10 - 5 - 5 = 0 doesn't mean there is an error in your calculations! It merely means that the result is zero.
Exacly the same is here. When a database returns no rows, it doesn't mean there is an error. It just meams that there is zero (no) data to return.
The opposite is true as well: if there is no error, it doesn't mean that there are rows found.
To see whether any row were returned or not, you need to fetch this very row.
Therefore, instead of checking execute() result, just fetch your row into a variable and then check whether it contains anything.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
Why would num_rows ever return null? It should always return a number representing the exact number of rows in the result set.
The following code returns null for num_rows:
<?php
include_once 'includes/psl-config.php'; // host, user, password, database
$db = new PDO('mysql:host='.HOST.';dbname='.DATABASE.';charset=utf8', USER, PASSWORD,
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
if ($res = $db->query("select 'Hello world!'")){
if (is_null($res)){
echo "Result is null<br>";
}
if (is_null($res->num_rows)){
echo "Num rows is null<br>";
} else {
echo "Rows returned: ".$res->num_rows."<br>";
}
while ($row = $res->fetch_row){
echo "Text returned = $row[0]<br>";
}
echo "Done";
} else {
echo "SQL error";
}
The resulting page displays "Num_rows is null".
This is so simple, I must be missing something!
The manual says num_rows always returns an int.
I use mysqli query, which stores the results by default. I don't need to use store_result.
Result is not null.
Since you are using PDO and not MySQLi, num_rows is not applicable. That being said, in general, I have found rowCount() is reliable when it comes to MySQL, however, as it states in the manual you should not rely on the rowCount() regarding SELECT statements:
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
The recommendation is to use a COUNT() sql statement instead for greatest reliability across database platforms:
$db->query("SELECT COUNT(*) FROM table_name");
You are using PDO. So it should be
$res->rowCount()
instead of
$res->num_rows
So I have written a script to insert an email address in a table but I want to check if the address already exists. So I begin with a prepared statement:
$statement = $db->prepare("SELECT * FROM `signups` WHERE `signups_email`= ? ");
$statement->bind_param('s',$email);
$statement->execute();
if($statement->num_rows < 1){
$statement->close(); //Free up the SQL result
//do the inserting code
} else {
echo "Email already exists";
}
Trouble is, ($statement->num_rows < 1) seems to always return true, even when I know there is an email in the database. I.e. it doesn't figure out that the address is already in the database.
My connection etc is fine as the //do the inserting code bit works fine.
Take a look at the documentation for mysqli_num_rows.
Returns the number of rows in the result set. The use of
mysqli_stmt_num_rows() depends on whether or not you used
mysqli_stmt_store_result() to buffer the entire result set in the
statement handle.
If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be
called immediately.
It looks like you need to call store_result() before you can check the number of rows.
Your statement fails if the email already exists in the DB. the if() should be
if ($statement->num_rows == 0) {
... email does not exist, insert it
} else {
... at least one record with that email exists
}
I have a a php page which updates a mySql database it works fine on my mac (localhost using mamp)
I made a check if its the connection but it appears to be that there is a connection
<?php require_once('connection.php'); ?>
<?php
$id = $_GET['id'];
$collumn = $_GET['collumn'];
$val = $_GET['val'];
// checking if there is a connection
if(!$connection){
echo "connectioned failed";
}
?>
<?php
$sqlUpdate = 'UPDATE plProducts.allPens SET '. "{$collumn}".' = '."'{$val}'".' WHERE allPens.prodId = '."'{$id}'".' LIMIT 1';
mysql_query($sqlUpdate);
// testing for errors
if ($sqlUpdate === false) {
// Checked this and echos NO errors.
echo "Query failed: " . mysql_error();
}
if (mysql_affected_rows() == 1) {
echo "updated";
} else {
echo "failed";
}?>
In the URL i pass in parameters and it looks like this: http://pathToSite.com/updateDB.php?id=17&collumn=prodid&val=4
Maybe this has to do with the hosting? isn' t this simple PHP mySql database updating? what can be wrong here?
Why on localhost it does work?
Why on live server it doesn't?
Let's start with troubleshooting your exact problem. Your query is failing for some reason. We can find out what that problem is by checking what comes back from mysql_query, and if it's boolean false, asking mysql_error what went wrong:
$sh = mysql_query($sqlUpdate);
if($sh === false) {
echo "Query failed: " . mysql_error();
exit;
}
You have other problems here. The largest is that your code suffers from an SQL Injection vulnerability. Let's say your script is called foo.php. If I request:
foo.php?collumn=prodId = NULL --
then your SQL will come out looking like:
UPDATE plProducts.allPens SET prodId = NULL -- = "" WHERE allPens.prodId = "" LIMIT 1
-- is an SQL comment.
I just managed to nuke all of the product IDs in your table.
The most effective way to stop SQL injection is to use prepared statements and placeholders. The "mysql" extension in PHP doesn't support them, so you'd also need to switch to either the must better mysqli extension, or the PDO extension.
Let's use a PDO prepared statement to make your query safe.
// Placeholders only work for *data*. We'll need to validate
// the column name another way. A list of columns that can be
// updated is very safe.
$safe_columns = array('a', 'b', 'c', 'd');
if(!in_array($collumn, $safe_columns))
die "Invalid column";
// Those question marks are the placeholders.
$sqlUpdate = "UPDATE plProducts.allPens SET $column = ? WHERE allPens.prodId = ? LIMIT 1";
$sh = $db->prepare($sqlUpdate);
// The entries in the array you pass to execute() are substituted
// into the query, replacing the placeholders.
$success = $sh->execute(array( $val, $id ));
// If PDO is configured to use warnings instead of exceptions, this will work.
// Otherwise, you'll need to worry about handling the exception...
if(!$success)
die "Oh no, it failed! MySQL says: " . join(' ', $db->errorInfo());
Most mysql functions return FALSE if they encounter an error. You should check for error conditions and if one occurs, output the error message. That will give you a better idea of where the problem occurred and what the nature of the problem is.
It's amazing how many programmers never check for error states, despite many examples in the PHP docs.
$link = mysql_connect(...);
if ($link === false) {
die(mysql_error());
}
$selected = mysql_select_db(...);
if ($selected === false) {
die(mysql_error());
}
$result = mysql_query(...);
if ($result === false) {
die(mysql_error());
}
Your call to mysql_query() is faulty; you're checking the contents of the variable you're passing in but the function call doesn't work that way. It returns a value which is what you should check. If the query failed, it returned false. If it returns data (like from a SELECT) it returns a resource handle. If it succeeds but doesn't return data (like from an INSERT) it returns true.
You also have some problems constructing your SQL. #Charles mentions SQL injection and suggests prepared statements. If you still want to construct a query string, then you need to use mysql_real_escape_string(). (But I would recommend you read up on the mysqli extension and use those functions instead.)
Secondly, you're concatenating strings with embedded substitution. This is silly. Do it this way instead:
$sqlUpdate = 'UPDATE plProducts.allPens SET '.$collumn.' = \''.$val.'\'
WHERE allPens.prodId = '.intval($id).' LIMIT 1';
If you must accept it in the querystring, you should also check that $collumn is set to a valid value before you use it. And emit and error page if it's not. Likewise, check that $id will turn into a number (use is_numeric()). All this is called defensive programming.