I have ci installed on a regular MAMP stack, and I’m working on this tutorial. However, I have only gone through the Created section, and currently I am getting a No database selected error.
Model:
<?php
class submit_model extends Model {
function submitForm($school, $district) {
$data = array(
'school' => $school,
'district' => $district
);
$this->db->insert('your_stats', $data);
}
}
View:
<?php $this->load->helper('form'); ?>
<?php echo form_open('main'); ?>
<p>
<?php echo form_input('school'); ?>
</p>
<p>
<?php echo form_input('district'); ?>
</p>
<p>
<?php echo form_submit('submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
Controller:
<?php
class Main extends controller {
function index() {
// Check if form is submitted
if ($this->input->post('submit')) {
$school = $this->input->xss_clean($this->input->post('school'));
$district = $this->input->xss_clean($this->input->post('district'));
$this->load->model('submit_model');
// Add the post
$this->submit_model->submitForm($school, $district);
}
$this->load->view('main_view');
}
}
database.php
$db['default']['hostname'] = "localhost:8889";
$db['default']['username'] = "root";
$db['default']['password'] = "root";
$db['default']['database'] = "stats_test";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
config.php
$config['base_url'] = "http://localhost:8888/ci/";
...
$config['index_page'] = "index.php";
...
$config['uri_protocol'] = "AUTO";
So, how come it’s giving me this error message?
A Database Error Occurred
Error Number: 1046
No database selected
INSERT INTO `your_stats` (`school`, `district`) VALUES ('TJHSST', 'FairFax')
Try leaving your password blank.
I think that's the default for WAMP and XAMPP. It could be for MAMP as well.
I assume you are (auto)loading the database class?
double check this, and also check the database name is correct.
Related
My Qr code is not working. I have already included my libraries consisting of CIqrcode and the qrcode. Is there anything that i missed? Any guides will be appreciated. Thank you
Controller:
class Testingpage extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Testingpagemodels');
$this->load->library('Ciqrcode');
}
function QRcode($try){
QRcode::png(
$try,
$outfile = false,
$level = QR_ECLEVEL_H,
$size= 5,
$margin =2,
);
}
public function fetchqr()
{
$list = $this->Testingpagemodels->get_datatables_testing();
$json = array();
$no = $_POST['start'];
foreach ($list as $rows) {
$no++;
$first=$rows->ID_NUMBER;
$json[]=array(
'<tr><th><center><img src="testingpage/QRcode/'.$first.'" width="110px"><br>'.$rows->NAME.'<br>'.$rows->DEPARTMENT.'</center></th>', //I'm calling the function of my QR here.
);
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Testingpagemodels->count_all_testing(),
"recordsFiltered" => $this->Testingpagemodels->count_filtered_testing(),
"data" => $json,
);
//output to json format
echo json_encode($output);
}
My Dear friend you did not mention your environment is local or live in case of the production server that might be the extension issue.to avoid that use the below mention code to display your image.
<?php
// $path is path where your image is stored.
$path = "assets/custom/img/img.jpg";
$type = pathinfo($path, PATHINFO_EXTENSION);
$file_data = file_get_contents($path);
$base64_img = 'data:image/' . $type . ';base64,' .
base64_encode($file_data);
?>
Solved.
From my "Config" i have deleted this:
From
$autoload['helper'] = array('url','html','email');
To
$autoload['helper'] = array('url','html');
Now it is working. Anyone who can help me why it is an error when I include it in autoload? Is there a conflict between qrcode and email? Thank you.
Can anyone tell me about how to build a connection between mysql and php page.
Please help me with this.
To start a connection You Might do Following code:-
<?php
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "test";
//change test with your server details//
$conn = mysqli_connect($servername,$username,$password,$dbname);
if ($conn)
{
//echo "connection ok";
}
else
{
echo "connection Failed";
}
?>
hope this code would help you .
Make conn.php file with this code inside and use $conn variable to prepare queries using prepared statement
if(!defined("connection")){
header('Location:error.php');
exit();
}
define("host","localhost");
define("user","mysql_user");
define("pass","password");
define("dbname","database_name");
$conn=new mysqli(host,user,pass,dbname);
if($conn->connect_error){
die("Failed to connect");
exit();
}
mysqli_set_charset($conn,"utf8mb4");
Use conn.php and $conn variable like this
Page.php
require_once("conn.php");
if($stmt = $conn->prepare($query)){
echo "prepared";
}
I'm struggling with the following problem. Some years ago, I've written a function to retrieve MYSQL results (multiple rows). Till PHP7, this code worked fine:
function MultipleRows($query)
{
global $dbhost, $dbname, $dbuser, $dbpass;
mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error! Couldn't <b>Connect</b>.");
mysql_select_db($dbname)
or die("Error! Couldn't <b>Select database</b>.");
$result = mysql_query($query)
or die("Error! Couldn't execute query.");
if(($result)&&(mysql_num_rows($result)>0))
{
return $result;
} else {
return false;
}
mysql_close();
}
Now in PHP7, this code doesn't seem to work anymore. After a lot of searching I came up with this as a replacement but unfortunately it doesn't work:
function MultipleRows($query)
{
$mysqli = new mysqli($dbhost, $dbpass, $dbuser, $dbname);
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
return $result;
$mysqli->close();
}
The function is meant to work with code like this:
$res_test = MultipleRows("SELECT id, name FROM table");
if($res_test)
{
while($res = mysql_fetch_array($res_test))
{
echo $res['id'].' '.$res['name'];
}
}
It's not a good option to rewrite the 'display code' (last fragment) because in that case I have to rewrite many lines in my website. Who can give me some help in this? Thanks in advance!
mysql extension has been dropped from PHP 7, after being deprecated in PHP 5.x.
You could rewrite function MultipleRows() using mysqli as follows:
function MultipleRows($query)
{
global $dbhost, $dbpass, $dbuser, $dbname;
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result = $mysqli->query($query);
if ($result !== FALSE)
$result = $result->fetch_all(MYSQLI_ASSOC);
$mysqli->close();
return $result;
}
A few remarks:
it is not a good idea to use global variables ($dbhost, $dbuser, $dbpass and $dbname)
this way of handling database queries makes you vulnerable to SQL injection attacks
I have a onBootstrap method in module.php file. I want to use this function to also store user log details into the mysql db. Not able to use persist and flush methods. Any thoughts, how to create a db connection?
Thanks in advance
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach('finish', array($this, 'outputCompress'), 100);
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$app = $e->getApplication();
$sm = $app->getServiceManager();
$auth = $sm->get('zfcuser_auth_service');
$routeMatch = $e->getRouteMatch();
// $name = $auth->getresolvedIdentity('id');
//echo "<pre>"; var_dump($auth); var_dump($routeMatch);
if($routeMatch && $auth){
$Userlog = new Userlog();
$Userlog->setUserid(10);
$Userlog->setUsername('abc');
$Userlog->setUrl_loaded('xyz');
$this->getObjectManager()->persist($Userlog);
$this->getObjectManager()->flush();
}
Am using drupal to manage my content. I want to search all my contents title and body and find how many times each word is repeated in the whole contents.
It may be by an sql query, but I have no experience with sql.
Any ideas?
This code searches the body field and ALL fields of ANY Content Types for a specific string. You can run it via command line. Say you save it as "fieldsearch.php", you can then run it as:
php fieldsearch.php "myStringForWhichToSearch"
You need to fill in your connection data and database name. It outputs the array of matching nodes but you can format that output into anything you'd like (I recommend csv).
<?php
//Set Parameters here
$env = "dev"; // Options [dev|prod] - Defaults to dev
$prodConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
$devConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
//Use the selected env settings
if($env == "prod"){
$connection = $prodConnection;
} else {
$connection = $devConnection;
}
function getTables($con, $database){
//Get the set of field tables
$sql = "SHOW TABLES FROM $database";
$result = mysqli_query($con, $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
return $tables;
}
function getFieldTables($con,$database){
$allTables = getTables($con, $database);
$fieldTables = array();
foreach($allTables as $key => $table){
if( isFieldTable($table) ){
$fieldTables[] = $table;
}
}
//add the common tables
$fieldTables[] = "field_data_body";
$fieldTables[] = "field_data_comment_body";
return $fieldTables;
}
function isFieldTable($table){
//echo $table . "\n";
if( stripos($table, "field_data_field") !== FALSE){
return TRUE;
}
}
//Set the search term here:
if (array_key_exists(1, $argv)) {
$searchString = $argv[1];
}
else {
die('usage: php fieldsearch.php "search string"' . "\n");
}
$databaseName = "myDatabaseName";
$outArray = array();
//Connect
$con=mysqli_connect($connection['host'],$connection['user'],$connection['pass'],$databasePrefix.$databaseNum);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//getFieldTables
$fieldTables = getFieldTables($con, $databaseName);
//Query each field tables data for the string in question
foreach($fieldTables as $key => $table){
//get Field value column name
$valueCol = str_replace("field_data_field_", '', $table);
$result = mysqli_query($con,"SELECT
entity_id
FROM
$table
WHERE
field_" . $valueCol . "_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray[$table][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
}
//Add the body table
$result = mysqli_query($con,"SELECT
entity_id
FROM
field_data_body
WHERE
body_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray['field_data_body'][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
var_dump($dataArray);