I am using this code to insert some values in MySql table:
<?php
mysql_connect("localhost","root","root");
mysql_select_db("bib");
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query);
// Display an appropriate message
if ($result)
echo "<p>Product successfully inserted!</p>";
else
echo "<p>There was a problem inserting the Book!</p>";
mysql_close();
?>
After running it into browser, the following error occurs:
"Apache HTTP Server has encountered a problem and needs to close. We are sorry for the inconvenience."
It seems that mysql_select_db("bib") statement causes it. Database is create , also table...
I am running php 5.3 and mysql 5.1 on windows xp sp 2.
Please any ideas are welcomed...
Thanks...
Any of the mysql_* functions can fail for various reasons. You have to check the return values and if a function indicates an error (usually by returning FALSE) your script has to react appropriately.
mysql_error($link) and mysql_errno($link) can give you more detailed information about the cause. But you don't want to show all the details to just any arbitrary user, see CWE-209: Information Exposure Through an Error Message.
If you don't pass the connection resource returned by mysql_connect() to subsequent mysql_* functions calls, php assumes the last successfully established connection. You shouldn't rely on that; better pass the link resource to the functions. a) If you ever have more than one connection per page you must pass it anyway. b) If there is no valid db connection the php-mysql modules tries to establish the default connection which is usually not what you want; it only takes up more time to fail ..again.
<?php
define('DEBUGOUTPUT', 1);
$mysql = mysql_connect("localhost","root","root");
if ( !$mysql ) {
foo('query failed', mysql_error());
}
$rc = mysql_select_db("bib", $mysql);
if ( !$rc) {
foo('select db', mysql_error($mysql));
}
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query, $mysql);
// Display an appropriate message
if ($result) {
echo "<p>Product successfully inserted!</p>";
}
else {
foo("There was a problem inserting the Book!", mysql_error($mysql), false);
}
mysql_close($mysql);
function foo($description, $detail, $die=false) {
echo '<pre>', htmlspecialchars($description), "</pre>\n";
if ( defined('DEBUGOUTPUT') && DEBUGOUTPUT ) {
echo '<pre>', htmlspecialchars($detail), "</pre>\n";
}
if ( $die ) {
die;
}
}
try this to connect to database:
$mysqlID = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die("Unable to connect to database");
mysql_select_db(DB_DATABASE) or die("Unable to select database ".DB_DATABASE);
also, try this as your insert query:
$query = "INSERT INTO carte (id, title) values ('".$id."', '".addslashes($titlu)."')
$result = mysql_query($query) or die(mysql_error());
By using die(), it will tell you where it has failed and why
Related
I've problem with mysql. I've PHP script, which returned array into json data from datebase.
I've message from 'echo' about successfully connection, but my result is equals which null of array.
In result on Explorer I've:
Connected successfully
query: SELECT name,id FROM rz_DWzZ'
result:
RESULT:[]
This is this script.
$conn = mysql_connect($servername, $username, $password);
mysql_select_db($database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$return_arr = array();
$qstring = "SELECT name,id FROM rz_DWzZ";
$result = mysql_query($qstring,$conn);
echo "<br>query: ".$qstring."<br>";
echo "<br>result: ".$result."<br>";
while ($row = mysql_fetch_assoc($result))//loop through the retrieved values
{
$row['name']=htmlentities(stripslashes($row['name']));
$row['id']=(int)$row['id'];
array_push($return_arr,$row);
}
mysql_close($conn);
echo "<br>RESULT:".json_encode($return_arr);
You didn't check for failure properly. mysql_*() functions return boolean FALSE on failure, which echo will print as a zero-length/invisible string.
You have to explicitly test for it:
$result = mysql_query(...) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^--method #1
if ($result === false) { // method #2
die(mysql_error());
}
And of course, you should NOT be using those functions anyways. They're obsolete/deprecated, and your code is now useless in newer versions of PHP. You should be using mysqli or PDO for any new development.
As well, you have numerous other bugs:
if ($conn->connect_error) {
the mysql_*() function library has NEVER been object-oriented. It's purely procedural, and has absolutely NO object support whatsoever. Therefore this connection test will always fail, as $conn->connect_error will always evaluate to null, which converts to boolean false as well, meaning you get a false positive for success.
I am working on converting some PHP code from mysql to mysqli. I have created an error and am unable to understand how to fix it. Any suggestions would be greatly appreciated.
The code looks like this:
<?php
include ("admin/includes/connect.php");
$query = "select * from posts order by 1 DESC LIMIT 0,5";
$run = mysqli_query($conn["___mysqli_ston"], $query);
while ($row=mysqli_fetch_array($run)){
$post_id = $row['post_id'];
$title = $row['post_title'];
$image = $row['post_image'];
?>
The error produced is: Fatal error: Cannot use object of type mysqli as array
The error is being called out on this line:
$run = mysqli_query($conn["___mysqli_ston"], $query);
In the line above $conn is a variable from the database connect file which has this code:
<?php
// Stored the db login credentials in separate file.
require("db_info.php");
// Supressing automated warnings which could give out clues to database user name, etc.
mysqli_report(MYSQLI_REPORT_STRICT);
// Try to open a connection to a MySQL server and catch any failure with a controlled error message.
try {
$conn=mysqli_connect ('localhost', $username, $password) or die ("$dberror1");
} catch (Exception $e ) {
echo "$dberror1";
//echo "message: " . $e->message; // Not used for live production site.
exit;
}
// Try to Set the active MySQL databaseand catch any failure with a controlled error message.
try {
$db_selected = mysqli_select_db($conn, $database) or die ("$dberror2");
} catch (Exception $e ) {
echo "$dberror2";
//echo "message: " . $e->message; // Not used for live production site.
exit;
// We want to stop supressing automated warnings after the database connection is completed.
mysqli_report(MYSQLI_REPORT_OFF);
}
?>
This line
$run = mysqli_query($conn["___mysqli_ston"], $query);
should be
$run = mysqli_query($conn, $query);
If you're migrating to mysqli, you should really read these docs at least.
The proper way to use a mysqli connection:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
?>
you should also consider utilizing mysqli's prepared statements
I've seen this question asked about a dozen times and the answers that seem to work for everyone are the same: add local-infile = 1 to [mysql], [mysqld], and add [client] loose-local-infile=1 to my.conf. I've done all of that as well as adding file permission to my DB user for . and I still get the same error.
I'm running MySQL 5.6 on a virtual Ubuntu 14.04 server. Can anyone let me know what I'm missing? I've got this working successfully on my live server which is a VPS running CentOS and MySQL 5.6 as well and I don't remember having to jump through any hoops to get it working, though it was some time ago that I set it up.
If it matters, I'm attempting this import through the below PHP function:
// Connect to a database without using prepared statements (for LOAD FILE feed commands)
// $query = query to execute; $rs = return a result set if true
function db_query_unprepared($query, $rs = false) {
// Create database connection
$link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$link) {
print 'Error connecting to MySQL Server. Errorcode: ' . mysqli_connect_error();
exit;
}
// Execute the query
if ($rs) {
$queryresults = array();
$counter = 0;
if (mysqli_multi_query($link, $query)) {
do {
// Save results to an array
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_assoc($result)) {
$queryresults[$counter][] = $row;
}
mysqli_free_result($result);
$counter++;
}
} while (mysqli_next_result($link));
}
else {
print mysqli_error($link);
}
}
else {
mysqli_multi_query($link, $query);
}
mysqli_close($link);
// Return the results
if (isset($queryresults)) {
return $queryresults;
}
}
That in turn is called like so:
db_query_unprepared('LOAD DATA LOCAL INFILE \'/path/to/mydatafile.csv' . '\' INTO TABLE feed_mydata FIELDS TERMINATED BY \',\' ENCLOSED BY \'"\' LINES TERMINATED BY \'\r\n\' IGNORE 1 LINES ( field1, field2, field3 )');
I have made a program using PHP and trying to store data into Local Server Xampp, but whenever i run my php script using this url:
http://127.0.0.1/test.php
Getting error message: {"StatusID":"0","Error":"Cannot save data!"}
Please someone help me in this how can i make it useful for me, please check below PHP Script:
<?php
$objConnect = mysql_connect("localhost","root","");
mysql_error($ObjConnect);
$objDB = mysql_select_db("registration_login");
mysql_error($ObjDB);
$strUsername = $_POST["sUsername"];
$strPassword = $_POST["sPassword"];
$strName = $_POST["sName"];
$strEmail = $_POST["sEmail"];
$strTel = $_POST["sTel"];
/*** Insert ***/
$strSQL = "INSERT INTO member (Username,Password,Name,Email,Tel)
VALUES (
'".$strUsername."',
'".$strPassword."',
'".$strName."',
'".$strEmail."',
'".$strTel."'
)
";
$objQuery = mysql_query($strSQL);
mysql_error($ObjQuery);
if(!$objQuery)
{
$arr["Status"] = "0";
$arr["Message"] = "Cannot Save Data!";
echo json_encode($arr);
exit();
}
else
{
$arr["Status"] = "1";
$arr["Message"] = "Register Successfully!";
echo json_encode($arr);
exit();
}
mysql_close($objConnect);
?>
Note: I have created registration_login database and member table under this DB..
Why don't you return the error reported by mysql or log it somewhere?
$objConnect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
You forgot to check the return the return value to see if this was successful - if it failed, the reason is in mysql_error()
$objDB = mysql_select_db(DB_DATABASE);
You forgot to check the return the return value to see if this was successful - if it failed, the reason is in mysql_error()
$objQuery = mysql_query($strSQL);
At least this time you check the return value - but you don't check what the error was.
BTW your script is wide open to SQL injection.
Convert mysql_* to PDO
What has that got to do with your post?
I have connected to a database for the first time with oop and stright away come up with an issue, below is my code which i'm struggling with:
$q = 'SELECT * FROM test';
$sqli->query($q);
if($sqli->query($q)){
echo "worked";
}
if($sqli->error){
echo $sqli->error;
}
I have checked for errors when connecting to the db and that works fine, but when I run this query I get no output, why? I expected an error or "worked", but have got neither.
Whats happening?
I have put some comments in the source code to help:
$q = 'SELECT * FROM test';
//$sqli is the result of a
//new mysqli("localhost", "user", "password", "database");
$resource = $sqli->query($q); // this returns a resource or false
if(!$resource) {
echo $sqli->error;
die; // do not process further
}
// process the results
$rows = $resource->fetch_all();
if ($rows) { // check if there are rows
echo "worked";
}
else {
echo "query is ok, but there are no rows";
}
You could also use $resource->fetch_object() which returns an object for output. Therefore if you wanted to print specific data from the result set, you would do something like
//table test.Name and test.Country
while ($rowobj = $resource->fetch_object()){
printf ("%s (%s)\n", $rowobj->Name, $rowobj->Country);
}
Good luck,
You could use this method, I hope it's what you are looking for. You will need to define the DB first. Then you can connect in OOP and test the connection is true or exit();
Let me know if this works for you. You can also define the DB in an external file and just do an include(); towards the top of your script for any pages needing connection to the DB.
define("SERVER","IP Address");
define("USER","DB USERNAME");
define("PASSWORD","DB PASSWORD");
define("DATABASE","DB NAME");
// This is for connection
$mysqli = new mysqli(SERVER, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}