MySQL MATCH, AGAINST not works with PDO - php

I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();
echo $appCount;
And it's not showing any results!
Thanks in advance for your help,
Marcell

Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);

Try
'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'
in phpmyadmin and see if it really returns anything.

try this
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$db->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
$stmt = $db->query($sql);
// If the SQL query is succesfully performed ($stmt not false)
if($stmt !== false) {
$cols = $stmt->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($stmt as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$db = null; // Disconnect
}
print_r($sth->errorInfo());
}
?>

enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
try {
// your code
} catch ( PDOException £e ) {
echo $e->getMessage();
exit();
}

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...

How to count rows in a while loop using pdo fetch

I was using mysqli_fetch_array and the counting was right until I changed to fetch(), which now only returns the total number of rows instead of returning each number for each row.
So for row one, I want to echo "1", and so on.
NEW NOTE :Everything else inside the while statement is returning correct values, except the counter which returns the total number of rows whereas I want a row number in the order that it was selected from the sql statement.
As requested. This is my connection.
I don't know if i'm suppose to be checking " $e->getMessage();" on every query since I'm using this connection for all my queries.
try {
$dbh = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8', 'usr', 'pwd',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
} catch (PDOException $e){
echo $e->getMessage();
}
This worked
$query = mysqli_query($con, 'SELECT * FROM music');
$count = 0;
while($row = mysqli_fetch_array($query)){
$count++;
echo $count;
}
The new doesn't work.
$query = $dbh->query('SELECT * FROM music');
$count = 0;
while($row = $query->fetch()){
$count++;
echo $count;
}
Works fine, use a try catch do see if your PDO connection is working.
try {
$dbh = new PDO('mysql:host=localhost;dbname=db', 'root', 'root',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$sql = 'SELECT * FROM music';
$sth = $dbh->query($sql);
$count = 0;
while($row = $sth->fetch()){
$count++;
echo $count;
}
I've just tested this and it works fine. Either your PDO connection is incorrect or your query returns no results. I suggest you var_dump($dbh) and see if it returns a PDO object or check that your query is correct. Is your table called music? It is case sensitive.
You also need to change your connection form mysqli to PDO
$mysqli = new mysqli("localhost", "user", "password", "database");
to
$dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password');
You can also throw PDO exceptions to see if any are occuring:
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
$conn->exec("SET CHARACTER SET utf8");
http://coursesweb.net/php-mysql/pdo-select-query-fetch
What about:
if ($pdo){
$query=$pdo->prepare("SELECT count(*) as cnt FROM music");
if($query->execute()){
$count = $query->fetch()[0];//or fetch()['cnt']
echo $count;
}
}
PDO have a little different behavior. This is a replacement for your mysqli.
try {
$dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password',array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// optional
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
));
$count = 0;
foreach ($dbh->query("SELECT * FROM `music`") as $row) {
$count++;
echo $count;
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
exit();
}
I hope that helped.
Try using PDO::FETCH_NUM to get the row count directly :-
$countquery = $dbh->query('SELECT COUNT(1) FROM music');
$rowCount = 0;
$rowCount = $countquery ->fetch(PDO::FETCH_NUM);
echo $rowCount;
//And then do another query for the real data if need be
* This makes use of a query to get the row count, and saves you the time taken by the while loop.

PDO mySql Connection

There is a link that I found a while back. What I would like to know is:
How do I query a simple SELECT * FROM table_name using PDO?
I tried playing around with the examples here but I was not getting any results back. All along I have been using the mysql_connect method which I dont want to use anymore. I would like to use following:
<?php
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="microict-intrasys"; // Database name //
//$id = 5;
try {
$conn = new PDO('mysql:$host;$db_name,', $username, $password);
$stmt = $conn->prepare('SELECT version FROM system_info');
// $stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) )
{
foreach($result as $row)
{
print_r($row);
}
}
else
{
echo "No rows returned.";
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>
First create the pdo instance and connect...
$db = new PDO('mysql:host=127.0.0.1;dbname=yourDBName;charset=utf8', 'username', 'password');
I use charset as well to have the correct formated data here... but you dont have to use it. Connection string could also look like
PDO("mysql:host=127.0.0.1;dbname=yourDBName" , $username, $password);
(using $username & $password here)
since working with pdo i ran into speed issues when i use localhost instead of 127.0.0.1 PDO seems to use the DNS to translate localhost into 127.0.0.1 and this causes speed. And im talking about seconds just for connecting to DBs
after connecting you can query like
$stmt = $db->query("SELECT * FROM table");
and than fetch could results like
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'].' '.$row['field2']; //etc...
}
or
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
so than you should have at least some result.... (simple way)
I guess your problem is...
accourdig to your source you have a issue in your connectionstring....
<?php
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="microict-intrasys"; // Database name
//$id = 5;
try {
$conn = new PDO('mysql:host={$host};dbname={$db_name}', $username, $password);
// you neeeeeed this--^ and this--^
$stmt = $conn->prepare('SELECT version FROM system_info');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) )
{
foreach($result as $row)
{
print_r($row);
}
}
else
{
echo "No rows returned.";
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>
you are missing some in your connection string! kinda typo
your parsed string looks like
"mysql:localhost;microict-intrasys"
and thats wrong. it must look like
//"mysql:host=localhost;dbname=microict-intrasys"
"mysql:host=127.0.0.1;dbname=microict-intrasys" // better
PDO Check
if (!defined('PDO::ATTR_DRIVER_NAME')) {
echo 'PDO unavailable';
}

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");

how to acess my database elements using the for loop?

I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];

Categories