Script to count two columns and echo result - php

I have a working SQL query that I'm trying to use in a small PHP script but getting Parse error, tried many variations. Hope you can help. End result would be to have a two field form with 'Date' and 'Channel No' then giving result count of number of 'channel' rows for a given date. Sorry fairly new PHP/SQL, thanks.
<?php
// Connect to MSSQL and select the database
$link = mssql_connect('localhost', 'root', '', 'jm_db');
mssql_select_db('jm_db');
// Select all our records from a table
$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
echo $sql;
?>
I have re-done the code but getting 'Warning: mysql_fetch_array() expects parameter 1 to be resource' and undefined variable.
<?php
// Create connection
$mysqli = new mysqli($localhost, $root, $jm_db);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
$results= array();
while ($result = mysql_fetch_array($sql)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
?>

You're missing a quote (Stack's syntax highlighting shows you), yet it should be replaced with an opening double quote and ending with the same. You can't use all single quotes.
I replaced the opening single quote with a double, along with a matching closing double quote.
$mysql_query = mssql_query ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
As a sidenote, you're echoing the wrong variable.
However, that is not how you would echo out results, but with a loop.
Something like, and replacing Fieldname with the one you want to use:
while ($row = mssql_fetch_assoc($mysql_query)) {
print $row['Fieldname'] . "\n";
}
or use mssql_fetch_array()
You can also use:
$results= array();
while ($result = mssql_fetch_array($mysql_query)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
For more information on Microsoft SQL Server's function, consult:
http://php.net/manual/en/book.mssql.php

$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
while($row=mssql_fetch_array($mysql_query))
{
echo $row[0];
}

$mysqli = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysql_query = mysqli ("SELECT COUNT(*) FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
while ($row = mysql_fetch_array($mysql_query, MYSQL_ASSOC)) {
echo ($row["channel"]);
}

this is a simple example with PDO
<?php
try {
$dns = 'mysql:host=localhost;dbname=jm_db';
$user = 'root';
$pass = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$cnx = new PDO( $dns, $user, $pass, $options );
$select = $cnx->query("SELECT COUNT(*) as count FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
$select->setFetchMode(PDO::FETCH_OBJ);
while( $row = $select->fetch() )
{
echo '<h1>', $row->count , '</h1>';
}
} catch ( Exception $e ) {
echo "Connect failed : ", $e->getMessage();
die();
}

Related

Count all rows in database where column equals to `YES`

I have a database crm_data in which I have multiple tables. Now I want to calculate all rows in whole database where column_name value is equal to YES. To calculate all rows in database I am using this mysql query.
My SQL Query:
$sql = $db_con2->prepare("SELECT SUM(TABLE_ROWS) AS all_rows FROM
INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'crm_data'");
$sql->execute();
$all_rows = $sql->fetchAll();
if (count($all_rows) > 0) {
foreach ($all_rows as $all_rows) {
echo $all_rows['all_rows'];
}
} else {
$all_rows = '0';
}
Thanks
What I did I went back to basics and used SHOW TABLES then I use table query SELECT * FROM $company WHERE rental_status = 'YES'. and I got the results.
BTW thanks guys giving me your suggestion.
Try this, i hope it works for you
// connect to Database.
$links = mysqli_connect($db_host, $db_username, $db_password, $db_name );
if($links === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//get total
$n = 'YES';
$result = mysqli_query($links,"SELECT Count(*) As column_name FROM crm_data WHERE column_name='".$n."'");
$rows = mysqli_num_rows($result);
if($rows){
$gt = mysqli_fetch_assoc($result);
$total = $gt["column_name"];
}
echo $total;
Using PDO as requested.
// using PDO
$servername = "localhost";
$username = "user";
$password = "pass";
try {
$conn = new PDO("mysql:host=$servername;dbname=dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
// call for the row count here.
$w='YES';
$rs = $conn->prepare("SELECT Count(*) As column_name FROM crm_data WHERE column_name='".$w."'");
$rs->execute();
$count = $rs->rowCount();
echo '<p>Total:'.$count.'</p>';
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
You're not querying the data in your database you're now querying the actual structure of the database, which is concerning.
Nevertheless...
SELECT SUM(`COLUMN_NAME`) FROM `INFORMATION_SCHEMA`.`COLUMNS` where `COLUMN_NAME` = 'YES' AND `TABLE_SCHEMA` = 'crm_data';
Is the query you are looking for...

php how to print sql values after mysql_fetch_array

i have SQL query :
SELECT countryCode FROM itins_countries WHERE (itinID = 5);
$countriesIndex = mysql_fetch_array($countriesQuery);
now, in another art of my code I would like to run on the "$countriesIndex" and print all the values it contain ("countryCode");
how can i do that?
while($row = mysql_fetch_array($countriesQuery)){
echo $row['column_name'];
///same for other columns
}
you can use the while loop to loop until all the array element has been printed
try this....
echo "<pre>";print_r($countriesIndex);
mysql_connect is deprecated...you can use mysqli_connect.
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($mysqli)) {
trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
}
mysqli_set_charset($mysqli, "utf8");
$sql = "SELECT countryCode FROM itins_countries WHERE (itinID = 5)";
$result = mysqli_query($mysqli, $sql);
$countries = [];
while($row = $result->fetch_assoc())
{
$users_arr[] = $row;
}
$result->close();
print_r($users_arr);

Could not be able to print Mysqli query result in php

I want to print result of a Mysqli query, But when I try to do as following way, It does not return any values or error. The code does not go through the while loop. What would be the wrong with my code, Please help me!
<?php
$mysqli = new mysqli("localhost", "root", "", "domains");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$part = explode(".", $str);
$part1 = $part[0];
$part2 = $part[1];
$sql = "SELECT
DomainCategory.Name
FROM
DomainName_Client,
DomainNameType,
DomainCategory,
OrderDomain_Client
WHERE
DomainName_Client.Name = '$part1'
AND DomainNameType.Name = '$part2'
AND DomainName_Client.TypeID = DomainNameType.ID
AND DomainCategory.ID = DomainName_Client.DomainCategoryID
AND OrderDomain_Client.DomainNameID = DomainName_Client.ID";
$result = $mysqli->query($sql);
if (!$result = $mysqli->query($sql)) {
die('There was an error running the query ' . $mysqli->error . ']');
}
while ($row = $result->fetch_assoc()) {
echo 'Total results: ' . $result->num_rows;
}
?>
First you check the number of results returning in the sql query using the following code and after that you print it using while or for loop.
echo $result->num_rows;

PHP: Unable to run same MySQL query several times

HTML FILE:
<form method="post" action="generate.php">
Product Reference(s): (if multiple, separate by ",")<br />
<input type="text" name="project_ref" value="REF123, REF124" />
<input type="submit" value="Generate" />
</form>
PHP FILE:
<?php
$ref_array = explode(',', $_POST['project_ref']);
foreach ($ref_array as &$ref) {
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `inventory` WHERE reference = '$ref' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Brand: " . $row["brand"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
}
?>
RESULTS:
Brand: Bose
0 results
But I actually wanted:
Brand: Bose
Brand: Beats
So the problem is that the MySQL query is not running for every array item. Its only executing the first item of the array.
Your input value has a space between the different refs: REF123, REF124
You can either explode on a comma & space:
$ref_array = explode(', ', $_POST['project_ref']);
Or trim the values:
$sql = "SELECT * FROM `inventory` WHERE reference = '" . trim($ref) . "' LIMIT 1";
It's also strongly recommended that you pass in $ref as a parameter, rather than a string literal:
http://php.net/manual/en/mysqli-stmt.bind-param.php
It looks like your issue is in your explode. The first value of the explode is correct the second (third, forth, etc.) will have a leading space. explode on ', ' instead of ',' or trim the results before using it.
But there are a few other things in this code. Don't create a new connection for each query, the single connection will work just reuse it. Second, use parameters or sanitize the value before you use it in the sql, this will help prevent sql injection attacks, a better way is to use PDO and use parameters. Last, change your query so that a single query returns all the results you need by using an IN clause.
<?php
$ref_array = explode(', ', $_POST['project_ref']);
$ref_IN = "";
foreach ($ref_array as $ref_val)
$ref_IN .= "'{$ref_val}', ";
$ref_IN = rtrim($ref_IN , ",");
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `inventory` WHERE reference IN ({$ref_IN}) GROUP BY reference";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Brand: " . $row["brand"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

mysqli update not updating although no error

I am trying to adapt my code, which works in a SELECT, to perform an UPDATE. Here, there is no error, but it does not update anything, it even does not even enter the loop. It is supposed to update the room type for the chosen days ($value).
I echoed all values to check them up and they are correct.
$bdd = mysqli_connect('localhost', 'root', '', 'webpage')
$roomty = 1;
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
foreach ($_SESSION['datesBooked_1_month'] as $key => $value)
{
$stmt = mysqli_stmt_init($bdd);
if ( mysqli_stmt_prepare( $stmt , "UPDATE '".$_SESSION['tab_from_month_year']."'
SET '".$_SESSION['roomtype_x']."'='".$_SESSION['roomtype_x']."' + ? WHERE day = ?"))
{
mysqli_stmt_bind_param( $stmt ,'is', $roomty , $value );
mysqli_stmt_execute( $stmt );
mysqli_stmt_close($stmt);
echo " Booked !<br /> ";
}
}
Please try the following code with the new MySql driver of PHP.
you put the quote for a integer value, that is wrong
do you named column with numbers? That is not comfortable.
Are you sure that $value is a string?
Why did you use $key => $value in the foreach loop?
Here the code:
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=webpage;host=127.0.0.1';
$user = 'root';
$password = 'dbpass'; #put here yor password
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
foreach $_SESSION['datesBooked_1_month'] as $value) {
#I hope that following variables don't contain space
$query = "UPDATE " .$_SESSION['tab_from_month_year'];
$temp = $_SESSION['roomtype_x'] + $roomty ;
#you wrote that $value is a string, are you sure?
$query .= " SET ".$_SESSION['roomtype_x']. "=$temp WHERE day='$value'" ;
$dbh->query($query);
}
I found out, the problem was the single quotes before the double quotes. It seems to be working very well with only double quotes like this :
if ( mysqli_stmt_prepare( $stmt , "UPDATE ".$_SESSION['tab_from_month_year']." SET ".$_SESSION['roomtype_x']." = ".$_SESSION['roomtype_x']." + ? WHERE day = ?"))
If this is the full code you need to select a database, currently the statement is being sent to the server but not to any database, there for you get no errors. You should use:
mysqli_select_db("You database goes here");

Categories