how do I check if mysqli connection is working? - php

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

Related

How to update status in database if status is empty without submitting a form in php?

How to update a status from database if status is empty in using php? I have this condition in php. I have this if condition that decides if $getstatus is empty it will update from database to Avail. I tried refreshing the page after querying the database. But it will not update in database. Is there anyway to update this without using form submit in php?
<?php
session_start();
include "includes/connection.php";
// Display all parking slots
$sql = $connection->prepare('SELECT * FROM parkingslot where parkingslotid = 1');
$sql->execute(); // execute query
$result = $sql->get_result(); // fetch result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getstatus = $row["status"];
echo $getstatus;
}
}
if (empty($getstatus)) {
$sql = $connection->prepare("UPDATE parkingslot SET status = 'Avail' where parkingslotid = 1 ");
}
?>
Codes in connection for connecting to database
connection.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// create connection
$connection = mysqli_connect($server,$username,$password);
// check connection
if(!$connection)
{
die("No connection found." . mysqli_connect_error());
}
else {
// select a database
$select_db = mysqli_select_db($connection,'smartparkingsystem');
if(!$select_db)
{
$sql = 'CREATE DATABASE sample';
// create database if no db found
if(mysqli_query($connection,$sql)) {
echo "Database Created";
}
else {
echo "Database not found" . mysqli_connect_error() . '\n';
}
}
else {
// Database already existed
// do nothing...
}
}
?>
If I understand your goal of: For row(s) whereparkingslotid=1 - Update status to 'Avail' but only if status is not currently set, this might help:
<?php
session_start();
include "includes/connection.php";
$connection->prepare("UPDATE `parkingslot` SET `status`=? WHERE `parkingslotid`=? AND (`status` IS NULL OR `status`=?)");
$connection->bind_param("sis", $status, $parkingslotid, $empty_str);
$status = 'Avail';
$parkingslotid = 1;
$empty_str = '';
$connection->execute();
echo $connection->affected_rows.' rows affected';
$connection->close();
?>
This saves a bit of processing by not checking with PHP first.
You can use this query:
"UPDATE parkingslot SET status = 'Avail' where status IS NULL OR status = '' "
Edited:
#lumonald gave the right anwser in the comment. You're not executing your second SQL statement.

Checking to see if ID is already in database, if it is don't INSERT it again

When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}

select data from DB and Insert new data in front of selected row

I want to insert a data into a mysql database, but I need to put some constrains over that insertion. And my code is not working for me.
Basically I have selected "departments" from the mysql db using html select tag and show that in dropdown. And now I want to insert subject and subject code in front of that row which is selected in the drop down. But the problem is my code is not working and show me error please help and checkout code.
This is code for inserting data from mysql database. It work's fine.
<code>
<select class="form-control" name="department">
<?php
$host="localhost";
$username = 'root';
$password = "";
$con = mysql_connect($host,$username,$password);
mysql_select_db('sims',$con);
// Checking connection
if (!$con){
echo ("Failed to connect to MySQL:. " .mysql_error($con));
}
else {
echo("db connect");
}
$result = mysql_query("SELECT * from `sims-reg-department`");
if($result == FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($result)){
?>
<option value="<?php '.row[dept-id];'?>"><?php echo $row["dept-name"];?></option>
<?php }
?>
</select>
</code>
This section is showing me errors:
<code>
<?php
if(isset($_POST['submit'])){
$dptname = $_POST["department"] or
$coursename = $_POST["course-name"] and
$coursecode = $_POST["course-code"];
if($coursename=="" or $coursecode=="" )
{
echo "Please fill all the fields before hit submitting button";
return true;
}
else
{
$q = "INSERT INTO `sims-reg-department`(`course-name`,`course-code`)VALUES ('$coursename','$coursecode') where '$dptname' LIKE `dept-name`";
}
$res = mysql_query($q) or die(mysql_error());
mysql_close($con);
}
?>
</code>

Using Dreamweaver, how can I populate a drop down list via PHP?

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>

live search with Jquery

I am trying to implement a live search on my site.
I am using a script somebody has already created. http://www.reynoldsftw.com/2009/03/live-mysql-database-search-with-jquery/
I have got the Jquery, css, html working correctly but am having troubles with the php.
I need to change it to contain my database information but everytime I do I recieve an error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\search.php on line 33
These are the details of my database:
database name: development
table name: links
Columns: id, sitename, siteurl, description, category
This is the php script
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "links";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
if(isset($_GET['query'])) { $query = $_GET['query']; } else { $query = ""; }
if(isset($_GET['type'])) { $type = $_GET['type']; } else { $query = "count"; }
if($type == "count")
{
$sql = mysql_query("SELECT count(url_id)
FROM urls
WHERE MATCH(url_url, url_title, url_desc)
AGAINST('$query' IN BOOLEAN MODE)");
$total = mysql_fetch_array($sql);
$num = $total[0];
echo $num;
}
if($type == "results")
{
$sql = mysql_query("SELECT url_url, url_title, url_desc
FROM urls
WHERE MATCH(url_url, url_title, url_desc)
AGAINST('$query' IN BOOLEAN MODE)");
while($array = mysql_fetch_array($sql)) {
$url_url = $array['url_url'];
$url_title = $array['url_title'];
$url_desc = $array['url_desc'];
echo "<div class=\"url-holder\">" . $url_title . "
<div class=\"url-desc\">" . $url_desc . "</div></div>";
}
}
mysql_close($conn);
?>
Can anybody help me input this database info correctly? I have tried many times but keep getting an error. Thanks in advance.
EDIT: IT IS CONNECTING TO THE DATABASE WITHOUT AN ERROR. CHECK HERE http://movieo.no-ip.org/
the mysql_query() call is failing an returning false instead of a resource. My bet is that mysql_select_db() is failing. This should show the error:
mysql_select_db($dbname) or die('Couldn\'t select DB: '.mysql_error());
Compare: database name: development to $dbname = "links";
I think you should change it to the right name.
As well as changing the $dbname to development, check your two SQL statements. They are selecting from the table urls instead of links.

Categories