Skip to content

mysqli_select_db return an error instead of false #8772

@saisilcastro

Description

@saisilcastro

Description

I am trying to verify if a database exists or not.
It it does not I create, if it does I just insert data into it.
But when call the function mysqli_select_db, instead of returning me false
it throws an error complaining that the database does not exist and stops my code.

<?php
    public function save($host,$user,$pass,$db){
		$connection = mysqli_connect($host, $user, $pass);
		if($connection){
			mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
			$createdDB = mysqli_select_db($connection,$db);
			if($createdDB === false){
				$dbCreator = "CREATE DATABASE IF NOT EXISTS ".$db;
				if(mysqli_query($connection, $dbCreator)){
					//echo "Database created successfully"."</br>";
				} else{
					echo "ERROR: Could not able to execute $sql. " . mysqli_error($connection);
					return 0;
				}
			}
			if($createdDB){
				$tableCreator = "CREATE TABLE IF NOT EXISTS `".$db."_tb` (".
							"`name` VARCHAR(64) NOT NULL,".
							"`price` REAL,".
							"`amount` SMALLINT,".
							"`barcode` BIGINT NOT NULL PRIMARY KEY,".
							"`lot` VARCHAR(64) NOT NULL,".
							"`manufactured` VARCHAR(10) NOT NULL,".
							"`maturity` VARCHAR(10) NOT NULL".
							");";
				$insert = "INSERT INTO ".$db."_tb (`name`, `price`, `amount`, `barcode`, `lot`, `manufactured`, `maturity`) ".
							  "SELECT ".
							  "\"$this->name\",".
							  "\"$this->price\",".
							  "\"$this->amount\",".
							  "\"$this->barcode\",".
							  "\"$this->lot\",".
							  "\"$this->manufactured\",".
							  "\"$this->maturity\"".
							  " FROM dual WHERE NOT EXISTS(SELECT * FROM $db"."_tb WHERE barcode = '$this->barcode')LIMIT 1;";
				if(mysqli_select_db($connection,$db)){
					if(mysqli_query($connection,$tableCreator));//echo "Tabela ".$db."_tb criada com sucesso.<br/>";
					if(mysqli_query($connection,$insert));//echo "Dados inseridos com sucesso em $db"."_tb<br/>";
				}
			}
			mysqli_close($connection);
			return 1;
		}
		return 0;
	}

Am I missing something?

PHP Version

php 8.1.7

Operating System

Windows 11

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions