Joining 2 statements to pull data from different tables - php

I have this code:
<?php
$data = mysql_query("SELECT * FROM repin WHERE new_pin_id LIKE ".$pinDetails->id) or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
?>
Obtained thanks to this article: Check field for identical number
I'm trying to use the detail I pulled: ".$info['from_pin_id']." to get data from another table. I'm looking for the best way to do this.
I thought about making it a variable and then running a second statement within the same <?php?> which would look something like this:
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
$newdata = "".$info['from_pin_id']."";
// new statement here.
?>
But 1. it won't work and 2. it looks messy.
What is the best way to achieve it?
FYI, what I need to do is use ".$info['from_pin_id']." to match a field in another table where the data is the same ID, then pull more info based on the match.

Use the following query:
"SELECT *
FROM repin r
LEFT JOIN otherTable o
ON o.someColumn = r.from_pin_id
WHERE r.new_pin_id LIKE '".$pinDetails->id."'"
Also, the argument to LIKE must be a string; you need to put quotes around it.

Related

SQL query result to string

I'm using SQL in Yii framework.
I need to show the person's latest active week (it's number and date).So I wrote following code:
public function latestWeek()
{
$datalogin=//the login is working fine
$sql ="SELECT w.number,MAX(w.start_date)
FROM tbl_person_week t, tbl_week w
WHERE t.person_id=$this->id AND t.week_id=w.id";
$query = mysqli_query($datalogin, $sql);
return $query;
}
Now , I checked this query on the server and it works fine (almost) but first thing: I need to convert it into string , because yii's CgridView can't read it , and I couldn't find a working solution for this.
Second: on the server , it gave me the max date indeed , but not it's correct number , but the first number available. How can I fix this as well?
Queries like that should never be used in objective framework. If yu want to execute your own query, you should do it this way:
$sql = "your sql code";
$array = Yii::app()->db->createCommand($sql)->queryAll();
As result you will get multidimensional array with selected columns and rows
If you want to use it in grid view, you should do it this way:
$count = Yii::app()->db->createCommand($sql)->queryScalar();
$dataProvider = new CSqlDataProvider($sql, array('totalItemCount'=>$count));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'grid-id',
'dataProvider'=> $dataProvider,
));
You can also use connection other than Yii::app()->db. Check CDbConnection class in docs.
edit: if you wanna use queries like mysql_fetch_assoc, check out also queryRow() method instead of queryAll()
Use Mysql_fetch _array
public function latestWeek()
{
$datalogin=//the login is working fine
$sql ="SELECT w.number,MAX(w.start_date)
FROM tbl_person_week t, tbl_week w
WHERE t.person_id=$this->id AND t.week_id=w.id";
$query = mysqli_query($datalogin, $sql);
while($row = mysqli_fetch_array($query)){
echo $row;
}
}
Assuming from your qu. that you want the week number and start date as one string, you have to concatenate the two columns in the sql.
You also need to specify that the week number is from the row with the maximum start date, which isn't as simple as you might first think.
I don't like injecting the person_id straight into SQL, it isn't awful in this case but is a bad habit to get into security-wise. There are binding methods available in the framework and I agree with Arek, that you should lean on the yii framework as much as possible.
To get the scalar string value, if you are insisting on using your own SQL.. I suggest the following:
$sql='
SELECT CONCAT('Week ',tw.number,' starting ',tw.start_date)
FROM tbl_week tw
JOIN (
SELECT MAX(twi.start_date) max_start_date
FROM tbl_week twi
JOIN tbl_person_week tpwi
ON tpwi.week_id = twi.id
AND tpwi.person_id = :person_id
) i
ON tw.start_date = i.max_start_date;
';
$command=Yii::app()->db->createCommand($sql);
$command->bindParam(":person_id", $this->id);
return $command->queryScalar();

PHP: strval in WHERE clause

Currently I have a piece of code that functions fine as it is. But what I really want to do is take the <?php if strval ..?> part and place it into the "SELECT * FROM projects" part as a WHERE clause. I am not sure whether this is possible or how to go about it. Any thoughts would be really valued. Hope this makes sense.
<?php
// ** User ID
$userid = $row_listelements ['id'];
// ** Projects
mysql_select_db($database_db, $db);
$query_activeusers = "SELECT * FROM projects ";
$activeusers = mysql_query($query_activeusers, $db) or die(mysql_error());
$row_activeusers = mysql_fetch_assoc($activeusers);
$totalRows_activeusers = mysql_num_rows($activeusers);
?>
<? do {?>
<?php if (!(strpos($row_activeusers['assignedto'], strval(",".$userid.",")) === false)) { ?>
<div><?=$row_activeusers['jobnumberdisplay'];?></div>
<?php } ?>
<? } while ($row_activeusers = mysql_fetch_assoc($activeusers)); ?>
<strong><?php echo $totalRows_activeusers; ?></strong>
In case your userid is a unique number, and I understand your question correctly, you could reach this by:
using IN - can handle strings and numbers (they have to be unique to make this work):
$query_activeusers = "SELECT * FROM projects WHERE ".$userid." IN (assignedto)";
or using FIND_IN_SET - can handle Strings and numbers is case sensitive:
$query_activeusers = "SELECT * FROM projects WHERE FIND_IN_SET('".$userid."', assignedto)"
But I think you should look at your database design. The trouble with including Foreign Keys in a delimited list like this is that whole point of a foreign key is to enable you to locate the information in the other table quickly, using Indexes. By implementing a database as it sounds you have, you have all sorts of issues to resolve.
i m not sure but maybe this will help you.
if(strval ...)
{
$where = "where field = $value";
}
Now you can use this $where variable in your select query. it will execute only if your if condition is satisfy.
If I understand your code correctly, you should use SQL LIKE, i.e. something like:
$query_activeusers = "SELECT * FROM projects WHERE assignedto LIKE '%," .
((int) $userid) . ",%'";
The cast to (int) here is done to ensure you have no special SQL characters in $userid - kind of cheap SQL quoting for values that are integers. You do not really need to use strval as concatenation into the string will convert that number into a string.

Variable out of scope when entering a while loop in php

I have a problem when trying to populate an array in php. It seems that once I enter a while loop with a mysql_fetch_assoc method I cannot populate my array. I've included the code below.
$params = $_REQUEST['params'];
$arr["status"]="ok";
$projects=array();
$files=array();
$titles=array();
$query = 'SELECT p.id as pid, f.fname as name, f.title FROM proj p INNER JOIN pic f ON f.projid=p.id WHERE p.catid=\'' . $params['category'] . '\' ORDER BY p.ordr, f.ordr';
require("../php/connect.php");
//select all projects from chosen category and pics from selected projects
$proj_result = mysql_query($query) or die ("Select failed");
//populate from rows
while($row = mysql_fetch_assoc($proj_result)){
$projects[]=$row["pid"];
$files[]=$row["name"];
$titles[]=$row["title"];
}
$arr["projects"]=$projects;
$arr["files"]=$files;
$arr["titles"]=$titles;
echo json_encode($arr);
The result: {"status":"ok","projects":[],"files":[],"titles":[]}
Thank You.
A while loop doesn't create a new scope, as you can see here: http://codepad.org/H1U3wXZD
About the code itself, here's a few suggestions:
0) I would consider having a database abstraction layer (PDO would be good enough).
1) Learn how to use JOIN's. It looks like you could fetch all the necessary information with a single query, something like:
SELECT p.id, p.proj, c.id, c.fname, c.title
FROM proj p
INNER JOIN pic c ON c.projid=p.id
WHERE catid='<your category>'
ORDER BY p.ordr, c.ordr
2) You should separate the code that gets data from the db from the code that constructs the HTML (?). Perhaps you could put that in another method. Something like:
if ($cmd == 'catSelect') {
$data = getData($params['category']);
foreach ($data as $value) {
// process data here
}
}
3) I take it you are using the generated JSON to send it via AJAX to a client. In that case, I would totally cut the fat (eg: generated markup) and send only essentials (picture id, title, fname and whatever else is essential) and generate the code on the client side. This will make your page load faster and save you and your visitors bandwidth.
my jquery/ajax client side script was not sending in category properly and therefore was no selecting any rows.
The above code will work.
Within the loop try something like this :
while($row = mysql_fetch_assoc($proj_result)){
$projects[]=$row["pid"];
$files[]=$row["name"];
$titles[]=$row["title"];
echo $row["pid"]." -- ".$row["name"]." -- ".$row["title"]."\n";
}
Do you get anything? Once you have tried it we will take it from there. My guess is that you aren't getting any data from MySQL.

Search entire table? PHP MySQL

I have made the following search script but can only search one table column when querying the database:
$query = "select * from explore where site_name like '%".$searchterm."%'";
I would like to know how I can search the entire table(explore). Also, I would need to fix this line of code:
echo "$num_found. ".($row['site_name'])." <br />";
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Thanks for any help, here is the entire script if needed:
<?php
// Set variables from form.
$searchterm = $_POST['searchterm'];
trim ($searchterm);
// Check if search term was entered.
if (!$serachterm)
{
echo "Please enter a search term.";
}
// Add slashes to search term.
if (!get_magic_quotes_gpc())
{
$searchterm = addcslashes($searchterm);
}
// Connects to database.
# $dbconn = new mysqli('localhost', 'root', 'root', 'ajax_demo');
if (mysqli_connect_errno())
{
echo "Could not connect to database. Please try again later.";
exit;
}
// Query the database.
$query = "select * from explore where site_name like '%".$searchterm."%'";
$result = $dbconn->query($query);
// Number of rows found.
$num_results = $result->num_rows;
echo "Found: ".$num_results."</p>";
// Loops through results.
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['site_name'])." <br />";
}
// Escape database.
$result->free();
$dbconn->close();
?>
Contrary to other answers, I think you want to use "OR" in your query, not "AND":
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
Replace other_column with the name of a second column. You can keep repeating the part I added for each of your columns.
Note: this is assuming that your variable $searchterm has already been escaped for the database, for example with $mysqli->real_escape_string($searchterm);. Always ensure that is the case, or better yet use parameterised queries.
Similarly when outputting your variables like $row['site_name'] always make sure you escape them for HTML, for example using htmlspecialchars($row['site_name']).
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Make sure that both forms use the same method (post in your example). The <form> tag should have the attribute method="post".
Also, what is wrong with the line of code you mentioned? Is there an error? It should work as far as I can tell.
A UNION query will provide results in a more optimized fashion than simply using OR. Please note that utilizing LIKE in such a manner will not allow you to utilize any indexes you may have on your table. You can use the following to provide a more optimized query at the expense of losing a few possible results:
$query = "SELECT * FROM explore WHERE site_name LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE other_field LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE third_field LIKE '".$searchterm."%'";
This query is probably as fast as you're going to get without using FULLTEXT searching. The downside, however, is that you can only match strings beginning with the searchterm.
To search other columns of table you need to add conditions to your sql
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
But if you don't know that I would strongly advise going through some sql tutorial...
Also I didn't see anything wrong with this line
echo "$num_found. ".($row['site_name'])." <br />";
What error message are you getting?
Just add 'AND column = "condition"' to the WHERE clause of your query.
Be careful with adding lots of LIKE % conditions as these can be very slow especially if using a front wild card. This causes the RDBMS to search every row. You can optimize if you use an index on the column and only a trailing wildcard.
You are searching the whole table, just limiting the results to those where the site_name like '%".$searchterm."%'. If you want to search everything from that table, you need to remove the WHERE clause
Here's the corrected line. You had a few too many quotes in it.
echo $num_found.".".($row['site_name'])." <br />";
Regarding displaying the message, you have a typo in your code:
// Check if search term was entered.
if (!$serachterm)
should be:
// Check if search term was entered.
if (!$searchterm)
In the code you have written, !$serachterm always evaluates to true because you never declared a variable $seracherm (note the typo).
your code is very bugy for sql injection first do
do this
$searchterm = htmlspecialchars($searchterm);
trim($searchterm);
next
$query = mysql_real_escape_string($query);
finaly your search looks like this
$query = "select * from explore where site_name like '%$searchterm%';

Using PHP with a MySQL db, how can I select everything from a row if i dont know what the columns are?

I have a table but I dont know what the columns are except for 1 column. There is only 1 permanent data value for each row, the rest of the columns are added and removed elsewhere. This isnt a problem for the query, i just do:
SELECT * FROM table
but for the php function bind_result() i need to give it variables for each column, which i do not know.
I think that once I have the columns in an array, I can do anther query and use call_user_func_array to bind the result to the array.
This seems like it would come up a lot so im wondering is there a standard way of doing this?
Couldn't you just do:
$result = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_assoc($result))
{
foreach ($row as $field => $value)
{
...
}
}
You could do
show columns from table;
And then parse that string to grab your column names.
You can also try the describe command, which is used to list all of the fields in a table and the data format of each field. Usage:
describe TableName;
you can use
$metadata = $prep_statement->result_metadata()
after you executed the statement and then loop through all result fields using something like
while( $field = $metadata->fetch_field() ) { }
the properties of $field are documented here: http://www.php.net/manual/en/mysqli-result.fetch-field.php

Categories