Searching MySQL DB using PHP - mysql

I use CodeIgniter + MySQL.
I am succeeding in running this query and parsing the result.
$var1 = $this->db->query("select title from stores where title like \"" . $str . "%\" union select title from coupons where title like \"" . $str . "%\"");
return $var1;
And in the controller, I parse the result() of this query to a JSON file using json_encode
But when I run the same query on another table, and follow the same step in parsing, I am facing parsing problems.
$var1 = $this->db->query("select tagword from tags where tagword like \"" . $str ."%\"");
Am I doing something wrong here?

Try echo-ing your SQL Statement
echo $this->db->last_query();
Then try Run SQL query/queries on your database for your debugging purpose

Related

Is it possible to know what UPDATE "WHERE" statement caused not to update without doing a second query?

I hava a Joomla DB Query (mysql) that updates something in the DB if all 3 WHERE clauses are met. I want to know if there is way to extract from the update mysql query which "WHERE" statement failed in updating?
I ask this because if COUNT = 1 (which means the DB is already updated and nothing should happen) I want to relay an error like "already updated before" instead of just "not updated".
I of course could do a select query if the update query fails but that means a second query and i was just wondering if there is a more elegant solution to this problem. Maybe a sql function i haven't heard of or something else. So i could do with just one database query.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->update($db->quoteName('#__table'));
$query->set($db->quoteName('field1') . ' = ' . $db->quote($value1))
->set($db->quoteName('field2') . ' = ' . $db->quote($value2));
if ($value3 !="") {
$query->set($db->quoteName('field3') . ' = ' . $db->quote($value3));
}
$query->where($db->quoteName('id') . ' = ' . $db->quote($rowid))
->where($db->quoteName('talentuid') . ' = ' . $db->quote($tid))
->where($db->quoteName('count') . ' = ' . $db->quote(0));
$db->setQuery($query);
$result = $db->execute();
// Check for affected rows.
if ($db->getAffectedRows() > 0) {
return '{"success": "true"}';
} else {
return '{"success": "false"}';
}

Export the result of MySQL query to my PC as a CSV file

I would like to export some MySQL-query results to my PC as a CSV-file. According to some contributions in the internet (e.g. here) it should work like the following:
mysql> SELECT 1,2,3,4,5 INTO OUTFILE 'C:\Users\MyPC\Desktop\numbers.csv';
ERROR 1 (HY000): Can't create/write to file 'C:\Users\MyPC\Desktop\numbers.csv' (Errorcode: 22 Invalid argument)
But theat leads to the given error. Waht am I doing wrong here? How can I save the output of my query as a csv ot a txt file?
P.S.: Im am using Windows
First of all, you didn't mention FROM which database you want the entrys.
SELECT 1,2,3,4,5 FROM ??????????????? INTO ...
With PHP you can do it like this:
$dz=fopen("file.csv", "w+");
$sql = "SELECT 1,2,3,4,5 FROM ?????????";
if ($result = $connectiontodatabase->query($sql)) {
while ($row = $result->fetch_assoc()) {
fputs($dz, $row['1'] . "\t" . $row['2'] . "\t" . $row['3' . "\t" . $row['4'] . "\t" . $row['5'] . "\t\n");
}}
fclose($dz);
$connectiontodatabase of course needs to be the new mysqli statement

Joomla Jdatabase query code with join does not work

I run the php code below within the 'Eval' section of a Fabrik form element. The code is supposed to return/put a number in a form field, but nothing appears in the form field.
When I used another query (refer to '$query-> ' lines) the code does work, so I get the impression that the query contains errors; however, when executing the related webpage with the form fields no sql error appears.
I have no idea what is wrong with the query(?)
Code:
$form_productname = 'testproduct';
$form_username = 'myname';
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
//$query->select($db->quoteName(array('a.id', 'b.productid')));
$query->select($db->quoteName('b.productid'));
$query->from($db->quoteName('#__products', 'b'));
$query->join('INNER', $db->quoteName('#__extendedreg_users', 'a') . ' ON (' . $db->quoteName('a.user_id') . ' = ' . $db->quoteName('b.owner') . ')
AND (' . $db->quoteName('a.cf_collectivename') . ' = ' . $db->quote($form_username) . ')
AND (' . $db->quoteName('b.productname') . ' = ' . $db->quote($form_productname)).')'.;
//echo $query;exit;
$db->setQuery($query);
$db->execute();
$results = $db->loadObjectList();
return count($results);
UPDATE: cause was syntax php error in where statement:
. $db->quote($form_productname)).
must be:
. $db->quote($form_productname).
You are not getting any errors because you are not catching any errors. Have a look at How to do SQL exception / error handling.
Do at least a $query->dump() and run your query in a console if you can't figure out what is wrong.
I don't understand why are you quoting the value you are comparing $form_username and $form_productname. But maybe it's late and I am tired.

Fetching data from database in php file

I am trying to fetch data from table. Table contains the data and query is true. Even why following query says $u and $t are not define. While condition becoming false.
I manually checked in database, it was showing results.
$url = "http://paulgraham.com/";
$user_id = "123";
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$result = mysqli_query($con,"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id."");
while ($row = #mysqli_fetch_array($result))
{
echo "hi";
$t = $row['title'];
$u = $row['url'];
}
echo "title is : $t";
echo "url is : $u";
Giving your SQL query :
"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id.""
You can see you are mixing url and userid... Change to :
"SELECT * FROM post_data WHERE userid =".$user_id." and url=".$url.""
Also define your $t and $u variables before your loop in case you have no record.
Next time, try to var_dump your generated query to test it.
If you were able to see the errors the DBMS is reporting back to PHP then you'd probably be able to work out what's wrong with the code.
Before the 'while' loop try...
print mysql_error();
(the obvious reason it's failing is that strings mut be quoted in SQL, and you've got the parameters the wrong way around)

Mysql update with ' symbol in variable

i have mysql query like this
mysql_query("UPDATE services SET sub_service='".$subbb_service."' WHERE sub_service='".$idd."' ") or die(mysql_error());
variable $subbb_service is with symbol '. Lets say it Hello' . So it fails query couse it looks like this
mysql_query("UPDATE services SET sub_service=' Hello'' WHERE sub_service='".$idd."' ") or die(mysql_error());
Now it has double '' and it dies. Maybe anyone could help me out?
Use mysql_real_escape_string:
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));