I ran var_dump(function_exists('mysqli_connect')); and it returned boolean true.
I am running the following code
<?php
$connect=mysqli_connect("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=mysqli_query($showtablequery);
while($showtablerow = mysqli_fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
It did not do anything. It did not print anything on the result webpage.
When I use mysql functions instead then it works fine.
What do I need to do to use mysqli function?
Oop
<?php
$mysqli = new mysqli("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=$mysqli->query($showtablequery);
while($showtablerow = $mysqli->fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
Even if you connected successfully, it cannot query the database without connection informatiokn.
Procedural
<?php
$connect=mysqli_connect("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=mysqli_query($connect, $showtablequery);
while($showtablerow = mysqli_fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
Instead of
$query_result=mysqli_query($showtablequery);
use
$query_result=$connect->query($showtablequery);
and instead of
$showtablerow = mysqli_fetch_array($query_result);
use
$showtablerow = $query_result->fetch_array();
Related
I am really new on php and I am trying to create my own php shop cart. After some research I got myself stuck in the "function products" below because seems to me it is not working properly. I expect to see the names of my products on my mysql database but it is not showing anything. My user name is noivaemd_etalhes, I am using my correct password and my database name is noivaemd_cart and I created on this database the table called Products with my list of products available. Can anybody help me to figure out what am I doing wrong on the php instructions below???? I appreciate any help.
<?php
session_start();
$page = 'index.php';
function products() {
$con = mysqli_connect("localhost", "noivaemd_etalhes", "mypassword", "noivaemd_cart") or die (mysqli_error());
$res = mysqli_query($con, "SELECT id, name, description, price FROM Products WHERE quantity > 0 ORDER BY id DESC");
if (mysqli_num_rows($res)==0) {
echo "<font family=verdana><font size=6px><font color= #90882C><font style=normal><font variant= normal><br>No products available<br></font>";
}
else{
while($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
}
}
?>
This code:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
Should be:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$get_row ['name'].'</p>';
}
As your title ask also tell how to check if the mysqli database connection is successful you can use the below code:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Reference link: http://www.php.net/manual/en/function.mysqli-connect.php
It's not good practice to connect to your database directly in your code. Open another file, and save it has 'dbconnect.php' or whatever you choose to name it. Save it in the same root.
Inside DB connect, you connect to the database like this:
<?php
$mysql_host = "localhost";
$mysql_user = "username";
$mysql_pass = "";
$mysql_dbname = "Products";
$conn_error = "Sorry, Could Not Connect";
if(!#mysql_connect($mysql_host,$mysql_user,$mysql_pass)||!#mysql_select_db($mysql_dbname)){
die($conn_error);
}
?>
In your index.php, inside your php tags, write 'require "dbconnect.php";'.
Then you get your values like this:
$InfoQuery = " SELECT id, product, name FROM table_name WHERE quantity>0 ORDER BY id DESC";
$Info = mysql_query($InfoQuery);
while($InfoRow=mysql_fetch_assoc($Info)){echo "<p>".$InfoRow['id']."<br>". $InfoRow['product']"."<br>". $InfoRow['name']."</p>";}
Edit: What you did wrong is in your while loop, you fetched the table data from $res when it should be fetched from $get_row
I'm trying to update my datebase from a php archive but i can't:
Before you ask: The names from db are written correctly and the if works too...
<?php
if(isset($_GET["ans"]) && isset($_GET["name"]))
{
include("con.php");
$con = con();
$answer = $_GET["ans"];
$nam = $_GET["name"];
if($answer="firefly" ||$answer="Firefly" ||$answer="FIREFLY")
{
$le=2;
$sc=50;
$update = "UPDATE User SET Level='$le', Score='$sc' where Name = '$nam'";
mysql_query($update,$con);
// header("Location: lv1b.php?n=$nam");
}
else {
echo "try again..." ;
}
}
?>*
This is the con.php...
<?php
function con()
{ $server="localhost"; $user="root"; $pass="";
$con= mysql_connect($server, $user,$pass);
mysql_select_db("games"); return $con;
}
Your if statement currently is assigning values, not testing equality, you can also skip the three tests by using one of the case conversion functions... so instead the if line should be:
if(strtolower($answer)=="firefly") {
Next up - as pointed out in comments - you're using the out-of-date MySQL library, you should rather be using MySQLI or PDO
Also you're wide open to SQL injection, you should be escaping any value you're using in MySQLi see mysqli_real_escape_string. In your example this means escaping the value of $nam
A potential alternative script-fragment (using MySQLi and the above if statement changes) might look something like:
<?php
$mysqli = new mysqli("localhost", /*username*/"root", /*pass*/"", /*dbname*/);
$name=$mysqli->real_escape_string($_GET["name"]);
if (strtolower($_GET["ans"])=="firefly") {
if (!$mysqli->query("UPDATE user SET level='2',score='50' ".
"WHERE name='$name'")) {
echo "query failed";
} else {
echo "Updated"
}
$mysqli->close();
} else {
echo "try again..";
}
Heres my code. Simple.
<?php
echo 'start<br>';
//Do the conntection
$checkconnection = mysql_connect('localhost', 'root', 'rootpass');
//Check if it's valid
if(!$checkconnection) {
echo 'CheckFailed';
} else{
echo 'CheckSucess';
}
echo 'end'; ?>
but I only can see 'start'. There is no 'CheckFailed', 'CheckSucess', 'end'
What should I do?
I already install mysql, create database, create tables, of course.
<?php
// Create connection
$con=mysqli_connect("localhost","root","root","database");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}
$result = mysqli_query($con, "SELECT * FROM table;");
?>
This question already has answers here:
Error: file is encrypted or is not a database
(7 answers)
Closed 5 years ago.
I have an SQLite database and am trying to connect to it with PHP. This is what I'm using:
<?php
$dbconn = sqlite_open('combadd.sqlite');
if ($dbconn) {
$result = sqlite_query($dbconn, "SELECT * FROM combo_calcs WHERE options='easy'");
var_dump(sqlite_fetch_array($result, SQLITE_ASSOC));
} else {
print "Connection to database failed!\n";
}
?>
However, I get this error:
Warning: sqlite_open() [function.sqlite-open]: file is encrypted or is not a database in C:\xampp\htdocs\deepthi\combadd\combadd_db.php on line 4
Connection to database failed!
What's wrong and how can I fix it?
Try to use PDO instead of sqlite_open:
$dir = 'sqlite:/[YOUR-PATH]/combadd.sqlite';
$dbh = new PDO($dir) or die("cannot open the database");
$query = "SELECT * FROM combo_calcs WHERE options='easy'";
foreach ($dbh->query($query) as $row)
{
echo $row[0];
}
$dbh = null; //This is how you close a PDO connection
Connecting To Database
Following PHP code shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned.
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('combadd.sqlite');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
?>
Now let's run above program to create our database test.db in the current directory. You can change your path as per your requirement. If database is successfully created then it will give following message:
Open database successfully
SELECT Operation
Following PHP program shows how we can fetch and display records
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('combadd.sqlite');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * FROM combo_calcs WHERE options='easy';
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "ID = ". $row['ID'] . "\n";
}
echo "Operation done successfully\n";
$db->close();
?>
<?php
if ($db = sqlite_open('sampleDB', 0666, $sqliteerror) ) {
$result = sqlite_query($db, 'select bar from foo');
var_dump(sqlite_fetch_array($result) );
} else {
die($sqliteerror);
}
?>
Make sure sqlite support is enable, check phpinfo()
One another solution to your problem is:
Using sqlite3 module instead
class DB extends SQLite3
{
function __construct( $file )
{
$this->open( $file );
}
}
$db = new DB( 'sampleDB.sqlite' );
I am trying to populate a drop-down list via PHP embedded in HTML.
Here is what I have so far:
<select name="ChapterList" id="ChapterList" style="width:120px;">
<?php
$username = "xxxxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxxxxxxx";
$host = "xxxxxxxx.mydomainwebhost.com";
#mysql_connect($host, $username, $password) or die("Unable to connect to database");
#mysql_select_db($database) or die("Unable to select database");
$query = "SELECT * FROM Chapters ORDER BY Id";
$ListOptions = mysql_query($query);
while($row = mysql_fetch_array($ListOptions))
{
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>"
}
?>
</select>
I know I am recieving the expected results because if I echo $row['ChapterName']; , the current values I have in the database are listed in the proper order, so why is it when I echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>" my list receives nothing at all?
You are missing a semi-colon at the end of your echo statement
while($row = mysql_fetch_array($ListOptions)) {
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>";
}
?>
Note: Start using mysqli_() functions as mysql_() are no more maintained by PHP team..
try using this
<?php
$form='';
$link = odbc_connect ('databasename', 'username', 'password');
if (!$link)
{
die('Could not connect: ' . odbc_error());
}
echo 'Connected successfully .<br>';
//Query the database
$sql = "SELECT * FROM Chapters ORDER BY Id ";
$result = odbc_exec($link,$sql);
$selectbox='<select id=combox name=Chapters >';
while($bin =odbc_fetch_array($result))
{
$selectbox.= "<option value=\"$bin[Chapters]\">$bin[FChapters]</option>";
}
odbc_close($link);
$selectbox.='</select>';
echo "Select Name".$selectbox;
?>
this code is working perfectly for me
Ok... so I solved my own question in a way.
What I discovered was that my php was being commented out via <--! -->. I merely changed the file extension to .php as opposed to .html. The drop-down list worked immediately and was populated with the proper values.
But this raises another question... how can I get inline PHP to work? My site is hosted with MyDomain. Is there a setting I am missing somewhere?
try to use this
<select>
while($row = mysql_fetch_array($ListOptions))
{
$id=$row['Id'];
$cname=$row['ChapterName'];
echo "<option value='$id'>$cname</option>";
}
?></select>
I have correct them just look at once,
<?php
$username = "xxxxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxxxxxxx";
$host = "xxxxxxxx.mydomainwebhost.com";
$dbc=#mysqli_connect($host, $username, $password,$database) or die("Unable to connect to database");
?>
<select name="ChapterList" id="ChapterList" style="width:120px;">
<?php
$query = "SELECT * FROM Chapters ORDER BY Id";
$ListOptions = mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($ListOptions,MYSQLI_ASSOC))
{
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>";
}
?>
</select>