$option = array();
$option['driver'] = 'mysql'; // Database driver name
$option['host'] = 'localhost'; // Database host name
$option['user'] = '*****'; // User for database authentication
$option['password'] = '********'; // Password for database authentication
$option['database'] = 'teste_dados'; // Database name
$db = JDatabase::getInstance( $option );
// Create a new query object.
$query = $db->getQuery(true);
/*
// Insert columns.
$columns = array('id_teste','testes','time');
// Insert values.
$values = array(4,'loucura3',date("h:i:s"));
// Prepare the insert query.
$query->insert($db->quoteName('teste1'));
$query->columns($db->quoteName($columns));
$query->values(implode(',', $values));
or
$query="INSERT INTO teste1('id_teste','testes','time') VALUES (4,'loucura3','".date("h:i:s")."')";
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
$db->execute();
Both options gives the following error message:
An error has occurred while processing your request.
You may not be able to visit this page because of:
an out-of-date bookmark/favourite
a mistyped address
a search engine that has an out-of-date listing for this site
you have no access to this page
Go to the Home Page
Home Page
If difficulties persist, please contact the System Administrator of this site and report the error below.
0 SQL=INSERT INTO teste1('id_teste','testes','time') VALUES (4,'loucura3','05:11:00')
I`ve seen some similar problems and their fixes and none of them workd for me any ideas?.
Try testing the sql script in mysql workbench or phpMyAdmin. Use backticks instead of single quotes around columns
Related
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.
I have tried like this:
$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:
$PartNo = $_POST['ManuPartNo’];
$BikeManufacturer = $_POST['BikeManufacturer’];
$BikeModel = $_POST['BikeModel’];
$BikeType = $_POST['BikeType’];
$BikeWheel = $_POST['BikeWheel’];
$BikeColour = $_POST['BikeColour’];
$BikeSpeed = $_POST['BikeSpeed’];
$BrakeType = $_POST['BrakeType’];
$FrameGender = $_POST['FrameGender’];
$AgeGroup = $_POST['AgeGroup’];
$DistFeatures = $_POST['DistFeatures’];
These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'
I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.
This is all running on a plesk server.
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.
// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Include db.php on every page where queries are executed and perform queries the following way
// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)
$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;
// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();
if($stmt){
echo "Row inserted";
}else{
echo "Error!";
}
See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.
You should try this
$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
If this doesn't work, enable the null property in sql values. So you can find out where the error originated.
It is possible to create connections to multiple databases using the JDatabase::getInstance() method. The following link points to a tutorial that describes how to create a helper file that makes it easy to create multiple JDatabase instances that point to different databases. You can create the database instances in the following manner using the custom helper class.
$db = JFactory::getDBO();
$db2 = MyDataHelper::getDBO2();
$db3 = MyDataHelper::getDBO3();
You can still get the default database object normally using JFactory.
You can add your own array of options to JDatabaseDriver, like so:
First database:
$db = JFactory::getDbo();
Second database:
$option2 = array();
$option2['driver'] = 'mysqli'; // Database driver name
$option2['host'] = 'localhost'; // Database host name
$option2['user'] = 'DB_USER'; // User for database authentication
$option2['password'] = 'DB_PASS'; // Password for database authentication
$option2['database'] = 'DB_NAME'; // Database name
$option2['prefix'] = 'jos_'; // Database prefix (may be empty)
$db2 = JDatabaseDriver::getInstance($option2);
Third database:
$option3 = array();
$option3['driver'] = 'mysqli'; // Database driver name
$option3['host'] = 'localhost'; // Database host name
$option3['user'] = 'DB_USER'; // User for database authentication
$option3['password'] = 'DB_PASS'; // Password for database authentication
$option3['database'] = 'DB_NAME'; // Database name
$option3['prefix'] = 'jos_'; // Database prefix (may be empty)
$db3 = JDatabaseDriver::getInstance($option3);
I have been following some videos and other sources on how to connect to database. I am just new to programming and i can't see where i have gone wrong with my connection. After heating the submit button on my form, the data seem to have been sent to database but after refreshing on my database, nothing is found. Your help is greatly appreciated.
Here is my database connection code.
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'student_registration';
$mysqli = new mysqli ($db_host, $db_user, $db_pass, $db_name);
if ($mysqli -> connect_errno){
printf ("connect failed: %s/n", $mysqli -> connect_error);
}
else printf ("connected to database");
?>
Here is my insertion code.
<?php
require_once("opendb.php");
if (isset($_POST['submit'])){
$department = $_POST['department'];
$post = $_POST['post'];
$description = $_POST['description'];
$responsibility = $_POST['responsibility'];
$requirement = $_POST['requirement'];
$date=#"$_POST[year]"."-".#"$_POST[month]"."-".#"$_POST[day]";
$query = "INSERT INTO posts VALUES('".$department."','".$post."','".$description."','".$responsibility."','".$requirement."','".$date."')";
$inset = mysqli_query($mysqli, $query );
if($inset){
}
?>
<script language="javascript">
alert("New Post Updated");
window.location="addpost.php";
</script>
<?php
} else{
?>
<script language="javascript">
alert("Post Updated did not update successfully Please try again");
window.location="addpost.php";
</script>
<?php
}
?>
The closing curly brace on if ($insert) is wrapping isset function. removing it renders the variables $department, $post etc as Unidentified variables.
Please SET PASSWORD for mysql database and then check.
mysql was working well without password,
BUT mysqli WON'T WORK with blank password.
example::
for me,as I'm using lampp
/opt/lampp/bin/mysqladmin -uroot password 'xyz'
PROBLEM #1: Incorrect SQL Statement
You need to specify which column to add it to by listing the corresponding column names in the database and then matching the order for the variable names.
If your column names are:
$department is inserted into department column
$post is inserted into post column
Corrected Code:(Change the column names to your corresponding column names)
$query = "INSERT INTO posts (department, post, description, responsiblity, requirement, date) VALUES ('$department','$post','$description','$responsibility','$requirement','$date')";
NOTE: Single quotations is enough for variables names in SQL statment
PROBLEM #2: $date Syntax Incorrect
Incorrect:
$date=#"$_POST[year]"."-".#"$_POST[month]"."-".#"$_POST[day]";
There is no quotation around year, month or day. you need a quotation surrounding them. Assign each POST to a variable and use the variables If you're just trying to get the date use the date() function
PROBLEM #3: Major Security Issue
Using mysqli_query without any filtering is like saying HACK MY SERVER !
Your database can easily be SQL Injected
Using direct queries like this is insecure overall !! Please use PHP prepared statements especially if this is a student registration form your planning to publish.
I am using flex builder 3 to insert into mysql database using php and everything is working perfectly in my localhost, the problem is when I deploy the project in the web server and run it, it connect to the database but i can't insert data ( it shows nothing when i insert data )
another stupid thing is in another piece of code for retrieving (select) data that works good on both my localhost and web server.
here is the php code:
<?php
$host = "******";
$user = "******";
$pass = "******";
$database = "******";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$nickname = $_POST['nickname'];
$steam = $_POST['steam'];
$c1 = $_POST['c1'];
$c2 = $_POST['c2'];
$c3 = $_POST['c3'];
$results = mysql_query("INSERT INTO `phantom`.`members` (`TF2_Nickname` ,`Steam_User_Name`,
`class1` ,`class2` ,`class3` ,`time`) VALUES ($nickname, $steam, $c1, $c2, $c3,NOW())");
?>
You need to declare the values as strings in your MySQL query as well:
"INSERT INTO `phantom`.`members` (`TF2_Nickname`, `Steam_User_Name`, `class1`, `class2`, `class3`, `time`)
VALUES ('$nickname', '$steam', '$c1', '$c2', '$c3', NOW())"
And you should also prepare them in some way to avoid that they are mistakenly treated as SQL command (see SQL Injection). PHP has the mysql_real_escape_string function to do that:
"INSERT INTO `phantom`.`members` (`TF2_Nickname`, `Steam_User_Name`, `class1`, `class2`, `class3`, `time`)
VALUES ('".mysql_real_escape_string($nickname)."', '".mysql_real_escape_string($steam)."', '".mysql_real_escape_string($c1)."', '".mysql_real_escape_string($c2)."', '".mysql_real_escape_string($c3)."', NOW())"
Insert into requires either user right or admin right. Check if by chance You didnt modify somewhere in the code these rights, e.g., You changed by hand the name of your admin... If it works the select it is because selecting doesnt need so many rights. Even non user status can retrieve info through select but insert needs special rights. You know your code so think about this difference
I am working on a project needing me to work with multiple database connections. From what I have read, I should be able to switch between connections in the query itself, something like:
mysql_query("SELECT * FROM user_types", $db_core)or die(mysql_error());
But I receive the error:
Table 'db_company.user_types' doesn't exist
So I can see it is looking at the incorrect db, it is grabbing the last mysql_select_db
I wouldn't want to have to re-select the database everytime but if that is the better way to go I can.
I have the databases selected like so:
<?
$currentpage = $_SERVER["REQUEST_URI"];
//Core DB
$db_core_host = "localhost";
$db_core_username = "root";
$db_core_password = "";
$db_core_name = "db_main";
//
$db_core = mysql_connect($db_core_host,$db_core_username,$db_core_password);
mysql_select_db($db_core_name, $db_core)or die(mysql_error());
//Company DB
$db_company_host = $company['db_server'];
$db_company_username = $company['db_username'];
$db_company_password = $company['db_password'];
$db_company_name = $company['db_name'];
//
$db_company = mysql_connect($db_company_host,$db_company_username,$db_company_password);
mysql_select_db($db_company_name, $db_company)or die(mysql_error());
?>
Not sure if it helps at all but when I echo either of the database connections I get Resource id #5
Use the db.table syntax in the query:
mysql_query("SELECT * FROM databas_ename.table_name", $db_core) or die(mysql_error());
The code you have in your question should work, except when both databases are on the same server. Take a look at the $new_link parameter of mysql_connect (see docs here): if you call it twice with the same server/user/pass, the connection will be re-used - which makes you end up with the mysql_select_db call on one connection influence the other one.
So if you have two different servers, or set $new_link to true, your code should work.