MySQL to PDO error - mysql

I have the following sql code:
$statement = "`maildb`";
$query = "SELECT COUNT(*) as `num` FROM {$statement}";
$row = mysql_fetch_array(mysql_query($query));
I am trying to transform to PDO... I have tried the following:
$statement = "`maildb`";
$query = $db->prepare("SELECT COUNT(*) as `num` FROM {$statement}");
$query->execute();
$row = $query->fetchAll(PDO::FETCH_ASSOC);
That results in: Fatal error: Call to a member function prepare() on a non-object in function.php on line 8.
I have also tried this before, which should do the same:
$query = $db->prepare("SELECT * FROM maildb");
$query->execute();
$row = $query->fetchAll(PDO::FETCH_ASSOC);
$num = count($row);
Any help?
Thank you!!

You are using $db which is not initialized. Please initialize it first by doing $db = new PDO( <connection details here> ). See PDO manual on PHP.net for more details.

You probably didn't instantiate $db. Therefore, it's not an object, thus you can't call a function from it

I think the error lies in this line:
$query = $db->prepare("SELECT COUNT(*) as `num` FROM {$statement}");
Instead try using:
$query = $db->prepare("SELECT COUNT(*) as `num` FROM ?");
$query->execute($statement);

Related

get the last id of the query with pdo php [duplicate]

I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

Can't get a simple SELECT to work

I have done this type of SELECT many times, but this time I can't get it to work. Any ideas, please?
$Name = "Dick";
$conn = mysqli_connect($server, $dbname, $dbpw, $dbuser);
$sql = "SELECT id FROM table WHERE $Name = table.first_name";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$customer_id = $row['id'];
Database::disconnect();
echo "customer id = " . $customer_id;
If you really DO have a table named table it would be more appropriate to use back ticks around the name since the word TABLE is a reserved word in MySQL. You should also use single quotes around your variable if it contains a string:
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
Other possible reasons if the query still doesn't work for you:
Make sure you have the connection parameters in the right order. It should be: mysqli_connect($server, $dbuser, $dbpw, $dbname).
You should be using fetch_array() instead of fetch_assoc() if you expect a one row result.
You are mixing PROCEDURAL STYLE with Object Oriented Style when using mysqli_connect() instead of mysqli(), at the same time using $result-> which is object oriented style. You should decide one style and stick with it.
This would be the procedural style of your query:
$Name = "Dick";
$conn = mysqli_connect($server, $dbuser, $dbpw, $dbname); // NOTE THE CHANGED ORDER OF CONNECTION PARAMETERS!
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
mysqli_free_result($result); // FREE RESULT SET
mysqli_close($conn); // CLOSE CONNECTION
And this would be the object oriented style:
$Name = "Dick";
$conn = new mysqli($server, $dbuser, $dbpw, $dbname);
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
$result->free(); // FREE RESULT SET
$conn->close(); // CLOSE CONNECTION
I would recommend naming your table something else than table since it's a reserved word and could get you into parsing problems. The same goes with field names. More reading: https://dev.mysql.com/doc/refman/5.5/en/keywords.html
More about mysqli_fetch_array() and differences in procedural style and object oriented style use: http://php.net/manual/en/mysqli-result.fetch-array.php
$sql = "SELECT id FROM table WHERE '$Name' = table.first_name";
You simply need to concat the variable like this:
$sql = "SELECT id FROM table WHERE " . $Name . " = table.first_name";

mysql query convert to mysqli

I am using the below query with the server setting as mysql in Joomla quite successfully, but can't get it run using the settings as mysqli in joomla Fabrik extension.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$sql = mysql_query("SELECT first_name,mobile FROM students WHERE
DAY(dob) = DAY(CURDATE()) AND
MONTH(dob) = MONTH(CURDATE())");
while($row = mysql_fetch_array($sql)) {
//mycode- to - send SMS
}
I have modified the above code for mysqli as below with no success:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$sql = mysqli_query("SELECT first_name,mobile FROM students WHERE
DAY(dob) = DAY(CURDATE()) AND
MONTH(dob) = MONTH(CURDATE())");
while($row = mysqli_fetch_array($sql)) {
//mycode- to - send SMS
}
What other changes I need to make in the above query so that I can use it using mysqli settings.
Thanks.
Joomla has it own database class so you don't need to use the likes of mysqli_*. Use something along the lines of the following:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('first_name', 'mobile')));
->from($db->quoteName('#__students'))
->where($db->quoteName('DAY(dob) = DAY(CURDATE())' AND 'MONTH(dob) = MONTH(CURDATE())'));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as $result) {
your code here
}
For more information in Joomla database queries, read this:
http://docs.joomla.org/Selecting_data_using_JDatabase
I have modified the query partly according to the suggestion by Lodder. My final query looks like this:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = "SELECT SUBSTRING_INDEX(name,' ',1)first_name,mobile FROM students WHERE
DAY(dob) = DAY(CURDATE()) AND
MONTH(dob) = MONTH(CURDATE())";
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as $result) {
$mobile = $result->mobile;
$name = $result->first_name;
//further code
}

Accessing data from database in joomla

I am using this query in Fabrik (Joomla Application) to pull the data from database, which is not working.
The same query with mysql syntax is working fine in PHPMYADMIN.
$db = FabrikWorker::getDbo(false, 2);
$query = $db->getQuery(true);
$query
->select('hostel_fee')
->from('hostel_fee AS a')
->join('INNER','students AS b ON (b.class = a.class)');
$db->setQuery($query);
$a = $db->loadResult();
return $a;
use the full queries like this
$db = &JFactory::getDBO();
$query = "SELECT m.id, m.title,m.level,mt.menutype FROM #__menu AS m
INNER JOIN #__menu_types AS mt ON mt.menutype = m.menutype
WHERE mt.menutype = m.menutype AND m.published = '1' ORDER BY mt.menutype,m.level";
$db->setQuery($query);
$rows = $db->loadObjectList();
OR
$rows = $db->loadResult();
Instead of using this
$db = FabrikWorker::getDbo(false, 2);
Use this.
$db =& JFactory::getDBO();
Or if you want to use any external database to connect to your extension you can use this
Connecting to an external database

Insert the values from the array into the column from the array?

I am trying to run the following but am getting the following mysql error ?
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO hqfjt_chronoforms_data_addupdatelead SET f9f2ec4270a751f4f34980c325e' at line 2
<?php
$user = $_POST[cf_uid];
$form = $_POST[uid];
$date = date("d-m-Y");
$query = mysql_query("UPDATE hqfjt_chronoforms_data_addupdatelead SET $form = $date
WHERE cf_uid = $user
")
or die(mysql_error());
?>
what I am trying to do, is use the $USER to find the correct user record, then in that user record find the column $form and insert the $date into it,
EDIT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Ok this gets me halfway there, but still an error >>
<?php
$user = $_POST[cf_id];
$form = $_POST[uid];
$date = date("d-m-Y");
$query = mysql_query("UPDATE hqfjt_chronoforms_data_addupdatelead SET '".$form."' = '".$date."' WHERE cf_id = '".$user."'")
or die(mysql_error());
?>
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''185cfb5654aacf3038e3f26491f227356b5d768f' = '30-12-2011' WHERE cf_id = '14'' at line 1
This is not correct:
First you are trying to execute both select and insert together and second insert don't have set command ... I think you need an update command
update hqfjt_chronoforms_data_addupdatelead SET $form = $date
WHERE $user = $user
OR, I think you are trying to do something like this
INSERT INTO hqfjt_chronoforms_data_addupdatelead SELECT * FROM
hqfjt_chronoforms_data_addupdatelead WHERE $user = $user
EDIT:
Try This:
<?php $user = $_POST["cf_uid"];
$form = $_POST["uid"];
$date = date("d-m-Y");
mysql_query('UPDATE hqfjt_chronoforms_data_addupdatelead SET "$form" = "$date"
WHERE cf_uid = "$user"') or die(mysql_error()); ?>
as per your comment you'd be fine just doing a
$query = "UPDATE table SET $forms = $date WHERE cf_uid = $user";
$success = mysql_query($query);
or you can put it all into one line as well. But if you're just looking to update there's no need to SELECT ALL the data from the user. That's what the "WHERE" is for.