Select Number of Values in Database Column - php

I have a mySQL table called palettes, and I want to return the number of links in the table. Basically, I want to return the number of values in the link column. (In this case, 6).
I tried using this code, but it didn't work. I'm a front-end dev, with NO knowledge of php or anything..
include "mysql.php";
$select_rows = $mysqli->query("SELECT COUNT(link) FROM palettes");
$rows = mysqli_fetch_array($select_rows);
$total = $rows[0];
echo $total;
The above code should or echoed 6, right? Selecting from column link
This is what my table looks like:

Use the WHERE clause with LIKE 'http%' and change your query to count id's that fit:
First, I'll assume your file 'mysql.php' has a connection to the database somewhere in the file like this:
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
$hostname = 'localhost';
$dbname = 'myDatabaseName';
$username = 'admin';
$password = 'myPassword';
$cxn = mysqli_connect($hostname, $username, $password, $dbname) or DIE('Connection to host is failed, perhaps the service is down!');
?>//End connect.php
Now you can try this:
include 'mysql.php';
$select_rows = mysqli_num_rows(mysqli_query($cxn, "SELECT id FROM palettes WHERE link LIKE 'http%'"));
echo $select_rows; //Should = 6

I would say place NULL in case you don't have the link available:
You can do it by making the Link column to allow NULL as default. You can make use of the COUNT(Link) in that case. This is recommended.
If you have to have empty string instead of NULLs.
select sum(if(Link != "",1,0)) counting from palettes;
Or if you can make sure all the links start with http/https
select sum(if(Link like "http%",1,0)) counting from palettes;

Related

php if statement always returns false

I know this is a really basic question but I am completely at my wits end. I have been working on this for two days. The if statement always returns false. I have tried === and == and copy to an $array and process outside the fetch $result loop. I have compared to a direct "name". I have outputed the ascii value of each letter of the returned string and compared that way to make sure I wasn't putting a space or something in somewhere. I've tried mysql and mysqli ways. I've tried OO style and Procedural style but here's the rub, This code was copy and pasted from my own site where it's working just fine in three other programs in my site.
<?php
SESSION_START();
if(!isset($_SESSION["uname"])){
require ('redirect.html');
die();
}// session is set close
$uname = $_SESSION["uname"];
$user_name = "xxxxxx";
$password = "xxxxxxx";
$database = "usersdata";
$server = "xxxxxxxxxx.ipagemysql.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM messages";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
//echo out values for visual comparison
echo $db_field['recipient']." ".$uname." ";
if($db_field['recipient'] === $uname){echo " match ";} else {echo " no match ";}
}// while loop db_field close
}// if db_found loop close
mysql_close($db_handle);
?>
As I stated this code works just fine in three other programs running on this very site. All I did was copy paste and change the db and fields. I even tried retyping it all from scratch just to make sure. Help me I'm melting....
Why would you return all the messages and then compare with every single message if the name matches. You can simply add a where clause to your query
SELECT * FROM messages WHERE recipient='uname value here'
Then you can check for the number of rows returned. If 0 rows are returned, there was no match.

How can I get a specific data using SQL select query?

I am trying to make a blog site.For this purpose I need to use a specific data from a specific field from my database table.To do that I wrote these code.
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
echo $img;
?>
My database connection is OK.It should print like this user_img1.jpg. But it prints the whole sql query like select image from news where uid=1. I run this code on phpmyadmin. It works! But it does not work in my php script.How can I do now?
You can not give the query as it is and expect result like in phpadmin.
For this first of all you have to connect to your DB like this
$con = mysqli_connect("localhost","my_user","my_password","my_db");
execute required query like this
$query22 = "select image from news where uid = 1";
$result22 = mysqli_query($con, $query22) or die (mysqli_error());
Get the result and display like this
while($rows = mysqli_fetch_array($result22, MYSQLI_BOTH))
{
echo "<br>Values in db: " . $rows['columnname'];
}
Also i advice you to take a look at these tutorials
http://codular.com/php-mysqli
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/
Please read some PHP 101 kind of tutorials on how to use PHP.
To get data from DB (in almost any language)
You need to connect to a DB. The connection gets you some sort of resource
You formulate your query (which you seem to have done)
You execute the query against the DB that you connected to (step #1)
You get a result (set)
You iterate over the result set to get the individual result(s); in your case the result set would be just one result (or row).
The examples to do this in PHP are very basic; please do your own lookup on net. This one seems good enough to get you started - http://www.w3schools.com/php/php_mysql_intro.asp
Try this,
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
$result=mysql_query($img);
while($row=mysql_fetch_array($result)){
echo '<img src="your_path_to_image/'.$row['image'].'" /> - '.$row['image'];
}
?>

Mysql Query, comparing values and assigning to PHP variables

I have done a fair bit of research into what i want to do, although i haven't found anything. I am not too sure if i am looking for the right thing :( I am also a little bit new to PHP and MySQL syntax, so please be kind.
I wish to perform the following in this order:
Connect to a database (DONE)
Query for a specific string (I think im done)
From here is gets a bit fuzzy :(
If a match is found for the variable, copy the whole row (I need other variables).
Assign the values from the SQL query to a PHP variables.
From there i will be right to carry on.
I have established the connection to the database with the following:
function connect() {
$dbname = 'database';
$dbuser = 'username';
$dbpass = 'password';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
}
And then calling the function connect();
I then wish to query the database for a particular value, for the sake of this argument i will use a static value. This is what i have:
mysql_select_db(DATABASENAME) or die( "Unable to select database");
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'";
$result=mysql_query($query);
From here i am not too sure how to compare the query result to see if it is a match (something along the lines of mysql rows?).
If there is a match, then i would like to obtain the entire row, and assign each value to a php variable.
I am not asking for you to do it for me, simply i kick in the right direction should be fine!
Hope it explains it enough :)
Thanks for your kind guidance
Ok. You will want to keep the connection to the mysql database somewhere. A common use is $conn.
So you would have
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
Then, either from the URL or Post, or just some variables you have sitting in your php file, you can query the database by putting the variables in the query itself. Also, here you can use $conn so that you have one place to connect to the database, in an include for example, and you won't have to make all of the connection string in each place you need to connect to the DB.
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%" . $varToCompare . "%'";
$result=mysql_query($query,$conn);
Above you are using a like. You may want to just look at doing .. Where column=$var.
Then you can use php to spin through the results into an array (for queries where would get multiple rows).
Where the hell you learned how to use MySQL in PHP ? The mysql_* functions are more then 10 years old and not maintained anymore. Community has already begun to work on deprecating them.
You should be using PDO or MySQLi for that.
// connection to database
$db = new PDO('mysql:host=localhost;dbname=datadump_pwmgr;charset=UTF-8',
'datadump_pwmgr',
'kzddim05xrgl');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// setting up prepared statement for the query
$statement = $db->prepare('SELECT * FROM table WHERE column LIKE :value');
$statement->bindParam(':value', $some_variable, PDO::PARAM_STR, 127);
// executing query and fetching first result
if ( $statement->execute())
{
$data = $statement->fetch(PDO::FETCH_OBJ);
var_dump( $data );
}
This should give you something like what you needed. Though, I would recommend to try this tutorial. And learning more about prepared statements could be useful too.
Also , if you are working with objects, then it is possible to create a single DB connection object , and pass it to multiple other classes to use it:
$pdo = new PDO('sqlite::memory:');
$a = new Foo( $pdo );
$b = new Bar( $pdo, 'something');
This way you pass both objects the same database connection, and you do not need to reinitialize it.
I think you're looking for something like this:
$count = mysql_num_rows($result);
//if there is more then 1 record retrieved from the database
if($count > 0)
{
//Do what ever you want to do here, which I think you want to be
while ($row = mysql_fetch_assoc($result))
{
echo $row["Columnname1"];
echo $row["Columnname2"];
echo $row["Columnname3"];
}
}
else
{
echo "There are no matches for this specific value";
}
You can get the queried data by rows as an associated array using mysql_fetch_array():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_array($data)) !== false)
{
echo "row = $row, name1 = " . $result["name1"] . ", name2 = " . $result["name2"];
$row ++;
}
... or as an objects using mysql_fetch_object():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_object($data)) !== false)
{
echo "row = $row, name1 = $result->name1, name2 = $result->name2";
$row ++;
}
I'm not too sure of what you want, but I can see one probable bug here: you're using LIKE in a way which means =: in order to have LIKE to behave like a like, you need some joker chars :
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'" // This will return all rows where column='VAUL'
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'" // This will return all rows where column='%VAUL%' // This will return any row containing 'VAUL' in column
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE'" // This will return all rows where column='%VAUL' // this will return all rows ending by VAUL. I guess you get it now :)
An to retrieve the actual results:
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'";
$result=mysql_query($query);
while (false !== ($row = mysql_fetch_assoc($result))) {
//here $row is an array containing all the data from your mysql row
}
Try to write the database connection in another page no need to use function and include that page in where ever you need.
ex: require_once 'dbConnect.php';
dbConnect.php consists:
<?php
$dbname = 'datadump_pwmgr';
$dbuser = 'datadump_pwmgr';
$dbpass = 'kzddim05xrgl';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
?>

How does one implement a MySQL database into a webpage?

I am a complete database newbie. So far, I know that I can connect to MySQL using PHP's mysql_connect() command, but apart from that, I really don't see how to take that data and put it onto a web page.
a) are there ways other than mysql_connect()
b) lets say I had a table of data in mysql and all I wanted was for that table (for example: list of names and telephone numbers) to now appear on my web page. I can't for the life of me find a tutorial for this.
<?
$database_name = "dbname";
$mysql_host = "localhost"; //almost always 'localhost'
$database_user = "dbuser";
$database_pwd = "dbpass";
$dbc = mysql_connect($mysql_host, $database_user, $database_pwd);
if(!$dbc)
{
die("We are currently experiencing very heavy traffic to our site, please be patient and try again shortly.");
}
$db = mysql_select_db($database_name);
if(!$db)
{
die("Failed to connect to database - check your database name.");
}
$sql = "SELECT * FROM `table` WHERE `field`= 'value'";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
// code here
// access variables like the following:
echo $row['field'].'<br />';
echo $row['field2'];
}
?>
Check out mysql_fetch_assoc mysql_fetch_array and mysql_fetch_object
This is the very basics, you will want to search for tutorials. There are many about.

Working with multiple databases in php/mysql

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.

Categories