I have been trying to create a PHP script that will periodically move "completed" rows from a table on my Joomla site to a different table. The query I wrote works just fine in PHPMyAdmin:
INSERT INTO my_calsgovdocs.sent_copy
SELECT * FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%';
DELETE FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%';
I attempted to translate it into some PHP code which could run inside Joomla, and I've pasted that code below. It returns an "Unexpected T_STRING" error which points to the line below which starts ->insert into, and it has now occurred to me that the script wouldn't work because "insert into" isn't a valid method name! So far I can't find an equivalent method to be used inside Joomla. This was my attempt at the code:
try
{
$db->transactionStart();
$query = $db->getQuery(true);
$query
->insert into($db->quoteName('sent_copy'))
->select('*')
->from($db->quoteName('entered_copy'))
->where($db->quoteName('Status') . ' LIKE ' . $db->quote('%Sent%') . ';')
->delete from($db->quoteName('entered_copy'))
->where($db->quoteName('Status') . ' LIKE ' . $db->quote('%Sent%'));
$db->setQuery($query);
$result = $db->execute();
$db->transactionCommit();
}
catch (Exception $e)
{
$db->transactionRollback();
JErrorPage::render($e);
}
Anyone have an idea how I can accomplish this inside Joomla? I'd prefer (as you may have noticed above) to do it in one transaction so that, if there's an error, I won't have a mess on my hands.
$db->setQuery allows being passed a query string as an argument instead of an object. See "preparing the query": https://docs.joomla.org/J1.5:Accessing_the_database_using_JDatabase
I've also suggested running two of these queries as part of the same transaction.
I unfortunately don't have a joomla installation handy to test this, please comment if you find it doesn't work.
try
{
$db->transactionStart();
$query = $db->getQuery(true);
$query1 = "INSERT INTO my_calsgovdocs.sent_copy
SELECT * FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%'";
$db->setQuery($query1);
$result1 = $db->execute();
$query2 = "DELETE FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%'";
$db->setQuery($query2);
$result2 = $db->execute();
$db->transactionCommit();
}
catch (Exception $e)
{
$db->transactionRollback();
JErrorPage::render($e);
}
You could try doing it in plain old php? Something like
$conf = JFactory::getConfig(); // load your config
try{
$link = mysqli_connect($conf->get('host'), $conf->get('user'),
$conf->get('password'), $conf->get('db'));
mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_WRITE);
mysqli_query($link, "INSERT INTO my_calsgovdocs.sent_copy
SELECT * FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%'");
mysqli_query($link, "DELETE FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%'");
mysqli_commit($link);
}
catch (Exception $e)
{
mysqli_rollback($link);
JErrorPage::render($e);
}
mysqli_close($link);
Related
i'm trying to create a multiple photo uploading script in php. All seems to be working fine except the update query. tried updating it manually in phpmyadmin and the problem of not updating persists don't know what to do can any experts help me solve this problem.
here is the update query:
try {
$sql1="update photos
set
filename='{$db_file_name}',
upload_date=now() where user='{$_SESSION['id']}' ";
$st1=$conn->prepare($sql1);
$st1->execute();
}
catch (Exception $exc) {
echo $exc->getMessage();
}
First of all, I would verify again whether all the variables you are using are correct (photos, filename, etc.). i.e. compare them letter by letter with your table. If that looks alright, a little more information wouldn't be bad. Are you getting any errors? If so, what are they saying? What else have you tried so far?
Moreover, I would suggest making your code a little easier to read like so:
/* create a prepared statement */
if ($st1 = $conn->prepare("UPDATE `photos` SET `filename` = ?, `upload_date` = ? WHERE `user` = ?")) {
/* bind parameters (ssi = string, string, integer)*/
$st1->bind_param("ssi", $db_file_name, now(), $_SESSION['id']);
/* execute query */
$st1->execute();
/* close statement */
$st1->close();
}
user is a keyword, better use backticks around it. See: https://dev.mysql.com/doc/refman/8.0/en/keywords.html
try {
$sql = "UPDATE `photos`
SET `filename` = :filename,
`upload_date` = NOW()
WHERE `user` = :sess_id";
$stmt = $conn->prepare($sql);
$stmt->bindValue(":sess_id", $_SESSION['id']);
$stmt->bindValue(":filename", $db_file_name);
$stmt->execute();
} catch (....) {
....
}
Perhaps better still, don't use keywords as column names, try userId.
I am using MySQLi in php to prevent SQL Injection with my table.
I have the following SQL command that works perfectly if input into phpMyAdmin.
INSERT INTO UsageData (MyID) SELECT * FROM (SELECT 'USER') AS tmp WHERE NOT EXISTS ( SELECT MyID FROM UsageData WHERE MyID = 'USER') LIMIT 1
Essentially it is intended to insert a new row with MyID as 'USER' if such a row does not already exist.
I have tried to do this with php like so
$query1 = "INSERT INTO UsageData (MyID) SELECT * FROM (SELECT ?) AS tmp WHERE NOT EXISTS ( SELECT MyID FROM UsageData WHERE MyID = ? ) LIMIT 1";
if ($statement1 = $database->prepare($query1)) {
$statement1->bind_param("ss", $inID, $inID);
$statement1->execute();
$statement1->close();
} else {
echo "Incorrect SQL 1\n";
echo "Query: ".$query1."\n";
echo $database->error."\n";
}
However this always results in the echoing of "Incorrect SQL". The error mentioned is "No tables used".
I have a SQL request sent right after it in the PHP that works perfectly but this one for some reason does not.
What am I doing incorrectly?
Okay, I'm going to assume that you've done the work to properly set up the database handler by doing something like $database = new pdo(...);
I'm a little foggy as to what happens when you put assignment statements inside the as an if condition. I would advise you to do the assignment before the if-else block and then test to see if ($statement1 === false) (testing for equivalence, not just equality) for an error. Otherwise, you can enclose $database->prepare(...) in a try-catch block as it emits a PDOException if something goes wrong like this:
try {
$statement1 = $database->prepare($query1);
} catch (PDOException $e) {
die("PDO Exception: " . $e->getCode() . ": " . $e->getMessage());
}
So I have a table called Userswhich contains a table structure like this:
Lets say I have a mysql table called 'signups' with the following values:
UID|Name|Regdate
1|Admin|2014-03-04 10:51:01
2|Demo|2014-05-04 09:51:05
I want to create a graph showing how many people signed up in one day. I used this SQL Query:
SELECT DATE(regdate) AS `Date` , COUNT(*) AS Signups FROM `users` GROUP BY DATE(regdate)
It gave me an output of:
Date|Signups
2014-03-04|1
2014-05-04|1
I wanted the output in a PHP File so I made this
<?php include_once("inc/db.php"); ?>
<?php
$query ="
SELECT DATE(regdate) AS `Date`
, COUNT(*) AS Signups
FROM `users`
GROUP BY
DATE(regdate)
";
$query_params = array(
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
echo $result;
?>
When I try to access the page, the result I get should be same thing I got from the SQL Query. However the result I get is 1. As you can see, I am using PDO. I am a beginner please help me please. :)
Do you use mysqli or PDO? Anyway execute does not do the job of returning the eventual result, assuming you use PDO, you have to:
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
foreach($stmt->fetchAll() as $fetch)
{
// do something
}
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
echo $result;
i've got a script which is meant to run a database query, however when trying to run this script i get the error Fatal error: Call to a member function fetch() on a non-object in /var/www/Quack/doSetup.php on line 209 - 209 being the while loop. I'm 99% sure this corresponds to there being a missing column in my database, however i can't work out which one it doesn't like. I was hoping this try catch system might tell me, it doesn't. Is there any way i can get this too give me more information on what it cannot find?
try{
$query = $db->query("SELECT articles . title FROM articles");
$query = $db->query("SELECT title FROM articles");
$SQLGetLogs = $conn -> query("SELECT `payments`.* , `plans`.`name` AS `planname`, `users`.`username` FROM `payments` LEFT JOIN `plans` ON `payments`.`plan` = `plans`.`ID` LEFT JOIN `users` ON `payments`.`user` = `users`.`ID` ORDER BY `ID` DESC");
while($getInfo = $SQLGetLogs -> fetch(PDO::FETCH_ASSOC)){
echo 'true';
}
}
catch(PDOException $e){echo 'My test failed: ' . $e->getMessage();}
You have to set error mode to throw exception to get them, else only internal error code is set:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The error you're getting is complaining that $SQLGetLogs is not a valid object, meaning that whatever you're setting it to is returning an invalid result.
The SQL statement at
$SQLGetLogs = $conn -> query("SELECT `payments`.* , `plans`.`name` AS `planname`, `users`.`username` FROM `payments` LEFT JOIN `plans` ON `payments`.`plan` = `plans`.`ID` LEFT JOIN `users` ON `payments`.`user` = `users`.`ID` ORDER BY `ID` DESC");
is probably failing or not producing the output you want. You should run the query manually in the database and check the output you get.
Should the $conn here be $db instead?
I am working on a project using PHP and MySQL.
I have an HTML table that has 3 columns into which I load data from my "Tasks" table in MySQL. The columns are: id, taskname and a button column that when clicked on, takes you to the Edit page for the relevant task (I pass the task id as a URL) - http://localhost/tasks/?edit&id=3
The problem arises when I try to load the details about this task. This is the code:
if(isset($_GET["id"]))
{
try
{
$sql = "SELECT * FROM tasks WHERE id = :id";
$result = $pdo->prepare($sql);
$result->bindValue(":id", $_GET["id"]);
$result = $pdo->query($sql);
}
catch(PDOException $e)
{
$error = "Error trying to load task - " . $e->getMessage();
include "error.php";
exit();
}
foreach($result as $task)
{
$tasktext = $task["task"];
$id = $task["id"];
}
$title = "Edit task";
$action = "edittask";
$button = "Edit task";
include 'form.php';
exit();
resetParameters();
I get the following error:
Error trying to load task - SQLSTATE[42000]: Syntax error or access violation: 1064 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 ':id' at line 1
When I replace the WHERE id = :id with WHERE id = 3 for example it works and loads the details about the task however I simply cannot get it to load the details about the task I have clicked on in the previous screen.
Could anyone spot anything wrong with my code/logic and point me in the right direction please?
You need to use execute() not query() when using prepared query's:
execute() PDOStatement::execute — Executes a prepared statement.
query() PDO::query — Executes an SQL statement.
Try:
<?php
try
{
$sql = "SELECT * FROM tasks WHERE id = :id";
$query = $pdo->prepare($sql);
$query->bindValue(":id", $_GET["id"]);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
$error = "Error trying to load task - " . $e->getMessage();
include "error.php";
exit();
}
?>