how to use getNumRows() in Joomla after a second query - mysql

I am developing a php script within the Joomla environment which queries the same table / database twice. Each time I need to know whether any matches are found.
It seemed that the best way would be to use the getNumRows(). The Joomla documentation is very specific on its use:
Miscellaneous Result Set Methods getNumRows()
getNumRows() will return the number of result rows found by the last
query and waiting to be read. To get a result from getNumRows() you
have to run it after the query and before you have retrieved any
results.
I follow this in my script. At the first query there is no problem, but the second query always throws up a warning - most likely because the getNumRows() call for the second time is after the retrieving results from the first query - which does not comply with the Joomla requirement.
Any ideas how to solve? Many thanks!
The part of my script in question reads:
$db = JFactory::getDBO();
$query = "SELECT * FROM #__art_mobiles WHERE user_agent_header='$ua'";
$db->setQuery($query);
$rowsAG = $db->getNumRows();
$replyAG = $db->loadRow();
if ($rowsAG == 0) {
//if no match check www.handsetdetection.com
//see https://www.handsetdetection.com/properties/vendormodel for current list of models in database together with headers
echo "not in local database - try external<br/>";
$prod = '';
if ($hd3->siteDetect()) {
$replyHD = $hd3->getReply();
$man = $replyHD['hd_specs']['general_vendor'];
$dev = $replyHD['hd_specs']['general_model'];
$os = $replyHD['hd_specs']['general_platform'];
echo "found in handsetdetection.com database<br/>";
//check for provisional match in local database
$query = "SELECT * FROM #__art_mobiles WHERE manufacturer='$man' AND device='$dev'";
$db->setQuery($query);
$rowsAGprov = $db->getNumRows();
$replyAGprov = $db->loadRow();
if ($rowsAGprov == 0) { **[ETC]**

I think this could be an issue with using $db->loadRow(); as getNumRows relies on an executed query.
For example you could try:
$db = JFactory::getDBO();
$query = "SELECT * FROM #__art_mobiles WHERE user_agent_header='$ua'";
$db->setQuery($query);
$replyAG = $db->query();
$rowsAG = $db->getNumRows();
And:
$query = "SELECT * FROM #__art_mobiles WHERE manufacturer='$man' AND device='$dev'";
$db->setQuery($query);
$replyAGprov = $db->query();
$rowsAGprov = $db->getNumRows();
Though I am not sure what/if the difference will be between the results returned from query and loadRow. It would be worth experimenting and seeing if this works.
Alternately, if you are only using getNumRows to see if a record exists, you could do some kind of check on your $replyAG variable instead. It again might be worth experimenting to see what loadRow returns if there are no results.

You need to add the following code before you write the the query:
$query = $db->getQuery(true);

You need to use
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->qn(array('id')))
->from($db->qn('#__social_notifications'))
->where($db->qn('status') . ' = ' . $db->q(0));
$db->setQuery($query);
$db->execute();
$resultData = $db->getNumRows();

Related

How to solve sql error " product portfolio has diversified to encompass a highly successful multi-brand' at line 1"

I am kind of new one for mysql and php. a week ago this code worked perfectly and when now I am trying it shows this error message
Error : You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 's product portfolio has diversified to encompass a highly
successful multi-brand' at line 1
I search how to solve that after spending a whole day, but couldn't figure it out.
I have tried similar questions here in stackoverflow, Yet I am stucked here.
A help would be really admired
Given below is my code
<?php
if(isset($_POST['upload']))
{ $company_name =$_POST['company_name'];
$service =$_POST['service'];
$email =$_POST['email'];
$password =$_POST['password'];
$details =$_POST['details'];
$fileName = $_FILES['Filename']['name'];
$fileName1 = $_FILES['Filename1']['name'];
$fileName2 = $_FILES['Filename2']['name'];
$fileName3 = $_FILES['Filename3']['name'];
$fileName4 = $_FILES['Filename4']['name'];
$target = "company_images/";
$fileTarget = $target.$fileName;
$fileTarget1 = $target.$fileName1;
$fileTarget2 = $target.$fileName2;
$fileTarget3 = $target.$fileName3;
$fileTarget4 = $target.$fileName4;
$tempFileName = $_FILES["Filename"]["tmp_name"];
$tempFileName1 = $_FILES["Filename1"]["tmp_name"];
$tempFileName2 = $_FILES["Filename2"]["tmp_name"];
$tempFileName3 = $_FILES["Filename3"]["tmp_name"];
$tempFileName4 = $_FILES["Filename4"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
$result1 = move_uploaded_file($tempFileName1,$fileTarget1);
$result2 = move_uploaded_file($tempFileName2,$fileTarget2);
$result3 = move_uploaded_file($tempFileName3,$fileTarget3);
$result4 = move_uploaded_file($tempFileName4,$fileTarget4);
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="pdf_uploads/";
// new file size in KB
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);//anthima
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$query = "INSERT INTO company_details( company_name,service, email, password, details,image_path,file_name,image_path1,file_name1,image_path2,file_name2,image_path3,file_name3,file,type,size,image_path4,file_name4) VALUES ('$company_name','$service','$email','$password','$details','$fileTarget','$fileName','$fileTarget1','$fileName1','$fileTarget2','$fileName2','$fileTarget3','$fileName3','$final_file','$file_type','$new_size','$fileTarget4','$fileName4')";
$con->query($query) or die("Error : ".mysqli_error($con));
mysqli_close($con);
}
}
?>
<?php
Given below is the test data error
VALUES ('singer','Hardware','singer#gmail.com','singer','Singer has been in Sr' at line 1
Because you never sanitize anything and put the data straight into your query,
$company_name =$_POST['company_name'];
$service =$_POST['service'];
$email =$_POST['email'];
$password =$_POST['password'];
$details =$_POST['details'];
...
$query = "INSERT INTO
company_details( company_name,service, email, password, details,image_path,file_name,image_path1,file_name1,image_path2,file_name2,image_path3,file_name3,file,type,size,image_path4,file_name4)
VALUES (
'$company_name','$service','$email','$password','$details','$fileTarget','$fileName','$fileTarget1','$fileName1','$fileTarget2','$fileName2','$fileTarget3','$fileName3','$final_file','$file_type','$new_size','$fileTarget4','$fileName4'
)";
your problem is most likely in the data
's product portfolio has diversified to encompass a highly successful multi-brand
Maybe you have unscaped apostrophes in your data, so you're kinda SQL-injecting yourself. The query ends before the string shown in the error.
The solution is to escape special chars before inserting like in this question: How do I escape only single quotes?
In your case, start with the details
$details = addcslashes($_POST['details'], "'");
or
$details = addslashes($_POST['details']);
But keep adding test scenarios for your code. E.g. what happens if company name gets something like Mc'Donaldson? What is the set of chars you want to accept for each field? Then you will know how to validate those fields and create your functions (or reuse something)

How to recursively get an array of child ids in Modx Revolution without using getChildIds

getChildIds can be very slow if running it against a large set of resources, so I am trying to write a query and some code to get all the child ids faster.
However I am getting different results from getChildIds & my script.
Can anyone see why these would be yielding different results?
Method using getChildIDs:
$parentDepth = isset($scriptProperties['parentDepth']) ? $scriptProperties['parentDepth'] : 5;
$parents = explode(',', $parents);
$children = array();
foreach ($parents as $parent){
$ids = $modx->getChildIds($parent,10,array('context' => 'web'));
foreach($ids as $id){
$children[] = $id;
}
}
echo ' number of children = ' . count($children);
method using queriees & a loop:
$comma_separated = implode(",", $parents);
$sql = "SELECT `id` from modx_site_content where `parent` IN (".$comma_separated.") and published = 1 and isfolder = 0 and deleted = 0 and hidemenu = 0;";
$results = $modx->query($sql);
$mychildren = array();
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
$mychildren[] = $row['id'];
}
for($i=0; $i <= 10; $i++){
$comma_separated = implode(",", $mychildren);
$sql = "SELECT `id` from modx_site_content where `parent` IN (".$comma_separated.") and published = 1 and isfolder = 0 and deleted = 0 and hidemenu = 0;";
$results = $modx->query($sql);
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
$mychildren[] = $row['id'];
}
}
echo ' number of children = ' . count($mychildren);
The getChildIDs method takes nearly 1.5 seconds to run and gives about 1100 results
The SQL/script method runs un under 0.1 second and gives 1700 results.
Either I'm not appending the child ids to the array properly ~or~ maybe getChildIDs is filtering out some other results?
does anyone have any clues as to what could be happening here?
You can try to use built-in method of pdoFetch.
$pdo = $modx->getService('pdoFetch');
$ids = $pdo->getChildIds('modResource', 0);
print_r($ids);
It also recursive, but can be better in some situations.
Of course, you need to install pdoTools from the repository first.
Looking at the code again, the discrepancy in results is pretty obvious now. I'm appending results to the child id array, it's inserting duplicates since one parent can have many children.
the solution to avoid duplicates:
$mychildren[$row['id']] = $row['id'];
getChildIds - is recursive, so it slower by default.

MySQL / PHP: cannot perform two separate queries on same database?

I have one database with two tables: "music" and "agenda".
But for some reason once I have queried one table, I cannot perform a similar query on the other table. Or in any case, its variables are empty.
I'd think I could just keep the connection open and perform a second query after the first "while". Like so:
<?php
mysql_connect('localhost', 'root', 'root');
mysql_select_db('erikverwey');
$result = mysql_query("SELECT * FROM agenda ORDER BY date DESC LIMIT 0, 2") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$count++;
$date[$count] = $row['date'];
$time[$count] = $row['time'];
$place[$count] = $row['place'];
$venue[$count] = $row['venue'];
$who[$count] = $row['who'];
$concert[$count] = $row['concert'];
$urlvenue[$count] = $row['urlvenue'];
}
$result2 = mysql_query("SELECT * FROM music ORDER BY id LIMIT 0, 5") or die(mysql_error());
while($row = mysql_fetch_array($result2)) {
$count++;
$song[$count] = $row['song'];
$artist[$count] = $row['artist'];
$duration[$count] = $row['duration'];
$url[$count] = $row['url'];
}
mysql_close();
?>
But no. In this case, all the variables from the table "music" remain empty.
I've been looking for an answer, but no luck. I'm still new to MySQL, though, so apologies beforehand if this is standard stuff. Thanks!
I found the glitch. Because the counter "$count" was used a second time, it started where it left off and couldn't find any data.
Use a different counter, also in the variables (!), and all is good.

Drupal 6 : Not able to fetch group_id(gid) from OG table

I am creating nodes pro-grammatically by fetching emails. Where I am splitting the subject of the mail for creating it for specific group & the title of the node.
Now I want to fetch the group_id by the description of the group and wrote query for it, but it's not working. Let me paste the code here..
list($group_name, $title_text) = explode(', ', $title);
$query = "SELECT * FROM {og} WHERE og_description = ' ".$group_name." ' ";
$group_details = db_query($query);
while ($group = db_fetch_object($group_details)) {
$gid = $group->nid;
}
echo $gid;
echo $gid is giving nothing. Though $group_name = 'Logo design' & gid = 1442 for it in table.
Is there anything I am missing here ?
Check out the following two pages , the examples give here does not use the single quotes around the placeholder in the query ($group_name - in your example) .
http://drupal.org/node/310072
One of the lines says "Note that placeholders should not be escaped or quoted regardless of their type" .
http://drupal.org/node/1407528
I have solved it. Here is the answer:-
$title = "ED's presentation, This content is for ed's presenation"; //This is the subject of the mail, which I am fetching.
list($group_name, $title_text) = explode(', ', $title);
$query = "SELECT nid FROM {og} WHERE og_description = '".$group_name."'";
$group_details = db_query($query);
while ($group = db_fetch_object($group_details)) {
{
$gid = $group->nid;
}
Thanks :)

MySQL Update Statement + File Upload

Been staring at this all day and can't seem to figure out why my update statement fails to update the field 'image_filename':
$fileName = $_FILES['image_filename'];
if($fileName["name"] <> ""){
$imageFile = $fileName['name'];
$destination = "../../../../assets/resources/images/".$fileName['name'];
move_uploaded_file($fileName['name'], $destination);
}
$updateSQL = sprintf("UPDATE content SET image_filename='$imageFile' WHERE id=%s",
GetSQLValueString($_POST['resource_id'], "int"));
mysql_select_db($database_conn_talent, $conn_talent);
$Result1 = mysql_query($updateSQL, $conn_talent) or die(mysql_error());
Can a SQL pro tell me what I"m missing? Much thanks in advance for your feedback!
You appear to be building a query, but never executing it. Also, Drupal'll handle all the sprintfing for you, if you let it.
$query = "UPDATE content SET image_filename='$imageFile' WHERE id=%i";
db_query($query, $_POST['resource_id']);