php PDO script refusing to give useful errors - php

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?

Related

Moving Rows Between Tables in Joomla

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

Submitting MySQL queries

$com_emails=mysql_real_escape_string($_POST['com_email']);
//$E=mysql_query("SELECT users.user_id FROM users WHERE users.email = '".$com_emails."' LIMIT 1");
$E=mysql_query("SELECT users.user_id FROM users WHERE users.email = 'go1#go1.com' LIMIT 1");
$E_row = mysql_fetch_row($E);
echo $E_row[0];
When I use the $com_emails the query does not seem to work. If I manually add the e-mail it works just fine. I've also tried doing "'$com_emails'" but nothing seems to working.
IS there a syntax issue I am missing that is obvious
Are you seeing an errors relating to mysql extensions being deprecated? I assume that you have established your db connection prior to the call to mysql_real_escape_string ? I'd suggest you try something like the following just to see what is going on:-
#error_reporting( E_ALL );
$com_emails=$_POST['com_email'];
$sql="SELECT `user_id` FROM `users` WHERE `email` = '".$com_emails."' LIMIT 1";
echo $sql;
/* Uncomment below if th sql looks correct etc */
/*
$E=mysql_query( $sql );
$E_row = mysql_fetch_row($E);
echo $E_row[0];
*/

PHP PDO, connection works buy query not executing

i am new to PDO.
Here is what i have done so far,
Created file "pdotest.php"
Code Inside that file
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$stmt = $conn->query("SELECT roomName FROM roomName.roomnames");
$results = $stmt->fetchAll();
$stmt->closeCursor();
print_r($results);
var_dump($results);
it should display some results from database but instead it says 500 internal server error in firebug, but no error on screen, its a white blank screen.
$stmt = $conn->query("SELECT roomName FROM roomName.roomnames");
try this instead:
$stmt = $conn->query("SELECT roomName FROM roomnames");
The select syntax is (basically):
SELECT column[, another_column, ...] FROM tablename[WHERE condition][ORDER BY some_column ASC/DESC];`
As you are setting the error mode to PDO::ERRMODE_EXCEPTION, you'll need to use try/catch to see any errors. This brings the burden of wrapping try/catch statements around your db queries.
Check your php log file for the exact php error - a white screen is shown as php is probably set up not to display errors on screen.
I'd check this part:
SELECT roomName FROM roomName.roomnames
Are you really trying to select roomName column from a table named roomName.roomnames? Should it not be the other way around like
SELECT roomnames FROM roomName
?

Warning: Invalid argument supplied for foreach() when retrieving data from database

I am attempting to retrieve data from two tables and echo the results out, the sql appears to be correct but it tells my the argument is invalid.
heres my code:
// Retrieve all information related to this post
function get_post_data($post_id){
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$sql = 'SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = $post_id';
$result = $dbh->query( $sql );
foreach($result as $row):
echo $row['img_id'];
endforeach;
}
The $post_id in your query won't be being expanded because the string is single quoted.
It should work better with:
$sql = "SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = $post_id";
or:
$sql = 'SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = '.$post_id;
You need to tell PDO to throw errors:
$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
That will probably tell you what is happening (except for a potential problem when creating the pdo object the line before it...).
I would also recommend switching to prepared statements to avoid potential sql injection or malformed query problems.
And I hope that is not your real password...

Trouble executing multiple-table mysql query from PHP

I am attempting to match rows in a mysql table using the values from table1.column1 and table2.column3 and then copy the value from table2.column2 into table1.column1 for each match. The query below does what I need to do, but only when I execute it manually (through phpmyadmin). When I try to execute it from PHP I receive the error Unknown column table1.column1 in 'field list'. Here is my PHP code:
<?php
mysql_connect($host,$user,$pass);
$db_selected = mysql_select_db($data);
$sql = "UPDATE table1 t1, table2 t2
SET t1.column1 = t2.column2
WHERE t1.column1 = t2.column3";
$result = mysql_query($sql);
if (!$result) {
echo mysql_error();
} ?>
I know that the mysql connection info works because I am able to execute other queries. From my research on the error it seems that I might need backticks around some part of the query but after several tries I can't figure out the correct way.
EDIT 1 - As requested here is the real query:
UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.post_type=wp_mf_posttypes.id
Outputs the error
Unknown column 'wp_mf_custom_groups.post_type' in 'field list'
Additional information I just realized might be conflicting with it. Before this happens I also renamed the table using:
RENAME TABLE wp_mf_module_groups TO wp_mf_custom_groups
Maybe since the table was just renamed it cant reference it?
Worked when I added backticks to the columns only after WHERE
UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.`post_type=wp_mf_posttypes.id
If query works with PHPmyadmin try this
<?php
$con = mysql_connect($host,$user,$pass) or die('Failed to connect');
$db_selected = mysql_select_db('db_name', $con);
$sql = "UPDATE table1 t1, table2 t2
SET t1.column1 = t2.column2
WHERE t1.column1 = t2.column3";
$result = mysql_query($sql, $con);
if (!$result) {
echo mysql_error();
} ?>

Categories