mysqli module not working - php

i'm trying to use mysqli module for PHP5 and it doesn't work. The module is activated in php.ini. What could be the problem?
<?php
require_once("class/guestbook.php");
$host = "localhost";
$user = "root";
$pass = "";
$db = "guestbook";
//Connect
$c = new mysqli($host, $user, $pass, $db);
//Check connection
if (mysqli_connect_errno()) {
printf("Connection failed! %s\n", mysqli_connect_error());
exit();
}
//Return the name of current database
if($result = $c->query("SELECT_DATABASE();")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
//Close connection
$c->close();
?>
Thank you!

The only thing wrong with your neat code, most probably, is your query itself.
SELECT_DATABASE(); // returns an error for obvious reasons
Means nothing to mysql. This does
SELECT DATABASE();
You don't see the error message because you don't check for errors on query execution. You are only looking for connection errors. Try an else{} block for $c->query and print the error message to see it.

Related

cant show the results of query in php from mysql

Hello I am new at php and mysql and I don't know what is wrong.
I cant show the results from query and the connection with mysql is successfully connected.
I don't use wampserver I just install php,mysql and Apache separately.
Thanks in advance.
Code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql="select * from `books`;";
$result=mysqli_query($conn,$sql);
if (!$result){
echo "query cannot execute";
};
?>
its only show me "query cannot execute"
You need to pass fourth parameter database name in mysqli_connect()
It would be
$conn = mysqli_connect($servername, $username, $password,"YOUR_DATABASE");
Read http://php.net/manual/en/mysqli.error.php to check error in query.
Read http://php.net/manual/en/mysqli-result.fetch-array.php
To fetch data from query result

Deletion of row in MySQL using php

I have been developing a CRUD application using PHP & MySQL database.
I was succeeded by creating, displaying, updation parts. But I stuck at the deletion part of a row from a database table.
I tried my best solving all the PHP shown errors but now in final it is now showing a message which I wrote to echo in case of failure.
I request someone to please help me with this problem.
Thankyou in advance.
Code I wrote for deletion:
//include database connection
include 'db_connect.php';
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query = "DELETE
FROM `grocery`
WHERE `GrocerID` ='".$mysqli->real_escape_string($_GET['id'])."'
limit 0,1";
//execute query
if( $mysqli->query($query) ){
//if successful deletion
echo "User was deleted.";
}else{
//if there's a database problem
echo "Database Error: Unable to delete record.";
}
$mysqli->close();
?>
Code I wrote for delete link in display table:
//just preparing the delete link to delete the record
echo "<a href='delete.php?id={$GrocerID}'>Delete</a>";
Code I wrote for db config:
<?php
//set connection variables
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
?>
I tried this and got working, can you update the code and see if this works?
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
// Delete row
if ($mysqli->query (sprintf( "DELETE FROM grocery WHERE email = '".$mysqli->real_escape_string($_GET['id'])."' LIMIT 1") )) {
printf ( "Affected Rows %d rows.\n", $mysqli->affected_rows );
}
I hope this helps.
Provide a connection :
if( $mysqli->query($con, $query) ){

How to extract desired row from Mysql database using PHP script

I have created one HTML form which takes input from user ,Now I need to search user inputed name in Mysql database and print details related to that user inputed name which is stored in Mysql database.
Below script is creating HTML form to take user input, Saved as "ProcessTracking.html".
<form action="details.php" method="get"/>
<h3 align="center"><FONT color=#CCFF66>ENTER SO NUMBER</h3>
<p align="center">
<input type="text" id="SO_Number" name="SO_Number"/>
</p>
<div style="text-align:center">
<button type="submit" value="SEARCH">
<img alt="ok" src=
"http://www.blueprintcss.org/blueprint/plugins/buttons/icons/tick.png"/>
SEARCH
</button>
</form>
Below PHP script named as "details.php"
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_assoc($result);
#printf ("SO_Number: %s \n",$row["SO_Number"])
#print_r($row);
printf ("SO_Number:");
printf($row["SO_Number"]);
printf ('--||--');
printf ("Name:");
printf($row["Name"]);
printf ('--||--');
$conn->close();
?>
Firstlly you are not using the $_GET['SO_Number'] parameter in a WHERE of SQL statement. Secondlly you are using both mysql and mysqli which are totaly diffrent and don't work together. For usage see mysqli_fetch_row() and mysqli_query(). Also use print_r($row);.
Here is the corrected code:
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_row($result);
print_r($row);
$conn->close();
?>
EDIT: Added code example.
You have mixed mysql and mysqli api together. Try using either one.
Note: mysql api is deprectaed as of php 5.5.0
1st Error
As saty says it is because of the syntax error you have in this line
print_r"$row";
which should be as print_r($row)
2nd Error
You're mixing mysql & mysqli
I am not sure about the table that you have.
Recommendation :
I would recommend you to turn on the error_reporting if not those errors will be in your errors_log file
Also for debugging your sql, you can first construct your sql query, run in the phpmyadmin or related tools for your query, then fire the query and make this done.
Note :
If you are using these code in online then the error_log will be in the directory where you execute this page. (But it may change according to your hosting)
If you are running in local machine the error log may locate according to the server you use...
You can find by printing the php's configuration by phpinfo and find for
error_log
May this thing will fix your issue
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
$so = $_POST['SO_Number'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM ProcessDetails WHERE SO_Number=$so");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row[SO_Number]);
$conn->close();
?>

Blank page when connect to database

I'm php begginer and i'm trying to connect database using XAMPP.
When i open my file there is not any error about connecting to database, but also there isn't "Connected successfully"; text, there is just blank page.
This is my code:
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "lala2";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
mysqli_close($conn);
?>
</body>
</html>
You used a mix between mysqli and mysql ! Here is the exact method name you should use to connect to a database, and its connection status checks :
MYSQLI style :
/* database connection information */
$server = "";
$user = "";
$password = "";
$database = "";
/* error messages */
$messErr_connectionDatabaseFailed = "Error : connection failed. Please try later.";
$link = new mysqli($server, $user, $password, $database);
/* If connection failed */
if (!$link) {
printf($messErr_connectionDatabaseFailed);
printf("<br />");
}
/* If connection successed */
else {
/* everything is ok, go to next part of you algorithm */
}
MYSQL style (depreciated due to performance and security issues) :
/* database connection information */
$server = "";
$user = "";
$password = "";
$database = "";
/* error messages */
$messErr_connectionDatabaseFailed = "Error : connection failed. Please try later.";
$link = mysql_connect($server, $user, $password);
/* if connection failed */
if (!$link) {
printf($messErr_connectionDatabaseFailed);
printf("<br />");
}
else {
/* selecting the database */
mysql_select_db($database, $link);
/* guessing your select db doesn't failed, next part of you algorithm here */
}
Please use the PDO functions to connect to the database instead. It will be easier to scale your app if you do decide to use different database drivers. Also "binding parameters" is considerably easier using PDO. For a quick intro on PDO, please read http://php.net/manual/en/intro.pdo.php
As far as why you are getting a blank page, there could be many reasons for that. You want to look at your log files first. On Windows, check the Event Logs. On Linux, your logs will be on /var/log. Add the following lines at the beginning of your script:
ini_set('display_errors',1);
error_reporting(E_ALL);
Please also look at this thread from StackOverflow: PHP produces a completely white page, no errors, logs, or headers.

How to check if my ODBC Data Source exist in PHP?

I have a simple project and that is to create a function that will check for mysql and odbc connection. I'm already done in creating the function for mysql, here's my sample code:
function check() {
$serverName = 'localhost';
$userName = 'root';
$password = '123';
$db = 'sample';
$conn = mysql_connect($serverName, $userName, $password);
mysql_select_db($db, $conn);
$trans = 'SELECT * FROM Labels';
$trans_result = mysql_query($trans, $conn);
if(!$trans_result) {
die(mysql_error());
} else {
echo "connected";
}
}
Well this one works for me when checking for the mysql connection. Now, my question is, is it possible to create something like this for checking my odbc data source connection? So that would be like
$conn = odbc_connect("spmuse1","" ,""); # Open connection.
$trans = "SELECT French FROM Labels";
$trans_result = odbc_exec($conn, $trans);
if(!$trans_result) {
echo "error?";
} else {
echo "connected";
}
You know what I mean? When I use this code, I always have 2 this error
Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect
Warning: odbc_exec(): supplied argument is not a valid ODBC-Link resource
Please help! Thanks.
First you need to decide vendor of odbc driver, I hope below example will works for you
<?php
// Configure connection parameters
$db_host = "server.mynetwork";
$db_server_name = "Dev_Server";
$db_name = "Dev_Data";
$db_file = 'c:\dbstorage\dev.db';
$db_conn_name = "php_script";
$db_user = "dbuser";
$db_pass = "dbpass";
$connect_string = "Driver={Adaptive Server Anywhere 8.0};".
"CommLinks=tcpip(Host=$db_host);".
"ServerName=$db_server_name;".
"DatabaseName=$db_name;".
"DatabaseFile=$db_file;".
"ConnectionName=$db_conn_name;".
"uid=$db_user;pwd=$db_pass";
// Connect to DB
$conn = odbc_connect($connect_string,'','');
// Query
$qry = "SELECT * FROM my_table";
// Get Result
$trans_result= odbc_exec($conn,$qry);
if(!$trans_result) {
echo "error?";
} else {
echo "connected";
}
?>
I spent several days looking for a simple answer, and came up with this, which works for me:
if (#odbc_connect("DBName","un","pw",SQL_CUR_USE_ODBC) == FALSE){
echo "Database does not exist";
} else {
$connection=odbc_connect("DBName","un","pw",SQL_CUR_USE_ODBC);
echo "Database exists";
}
The # suppresses the basic error if the database does not exist, so the connection try will just return false. Of course if the connection is good, then it creates the connection object.

Categories