mysql - combining columns and tables - mysql

I have a site where I have a database for all accounts and whatnot, and another for storing actions that the user has done on the site.
Each user has their own table but I want to combine the data of each user group (all users that are "linked together") and order that data in the time the actions took place.
Here's what I have;
<?php
$query = "SELECT `TALKING_TO` FROM `nnn_instant_messaging` WHERE `AUTHOR` = '" . DISPLAY_NAME . "' AND `TALKING_TO` != ''";
$query = mysql_query( $query, $CON ) or die( "_error_ " . mysql_error());
if( mysql_num_rows( $query ) != 0 ) {
$table_str = "";
$select_ref_clause = "( ";
$select_time_stamp_clause = "( ";
while( $row = mysql_fetch_array( $query ) ) {
$table_str .= "`actvbiz_networks`.`" . $row['TALKING_TO'] . "`, ";
$select_ref_clause .= "`actvbiz_networks`.`" . $row['TALKING_TO'] . ".REF`, ";
$select_time_stamp_clause .= "`actvbiz_networks`.`" . $row['TALKING_TO'] . ".TIME_STAMP`, ";
}
$table_str = $table_str . "`actvbiz_networks`.`" . DISPLAY_NAME . "`";
$select_ref_clause = substr($select_ref_clause, 0, -2) . ") AS `REF`, ";
$select_time_stamp_clause = substr($select_time_stamp_clause, 0, -2) . " ) AS `TIME_STAMP`";
}else{
$table_str = "`actvbiz_networks`.`" . DISPLAY_NAME . "`";
$select_ref_clause = "`REF`, ";
$select_time_stamp_clause = "`TIME_STAMP`";
}
$where_clause = $select_ref_clause . $select_time_stamp_clause;
$query = "SELECT " . $where_clause . " FROM " . $table_str . " ORDER BY TIME_STAMP";
die($query);
$query = mysql_query( $query, $CON ) or die( "_error_ " . mysql_error());
if( mysql_num_rows( $query ) != 0 ) {
}else{
?>
<p>Currently no actions have taken place in your network.</p>
<?php
}
?>
The code above returns the sql statement:
SELECT ( `actvbiz_networks`.`john_doe.REF`, `actvbiz_networks`.`Emmalene_Jackson.REF`) AS `REF`, ( `actvbiz_networks`.`john_doe.TIME_STAMP`, `actvbiz_networks`.`Emmalene_Jackson.TIME_STAMP` ) AS `TIME_STAMP` FROM `actvbiz_networks`.`john_doe`, `actvbiz_networks`.`Emmalene_Jackson`, `actvbiz_networks`.`act_web_designs` ORDER BY TIME_STAMP
I really am learning on my feet with SQL.
Its not the PHP I have a problem with (I can quite happily code away with PHP); It's just help with the SQL statement.
Any help much appreciated.

Didn't take the time to through your code, but from the question it sounds like you want UNION.
SELECT
3 AS a
UNION SELECT
2 AS a
UNION SELECT
1 AS a
ORDER BY a
Gives
a
=
1
2
3
EDIT: So perhaps something like this?
DROP TEMPORARY TABLE IF EXISTS t1;
DROP TEMPORARY TABLE IF EXISTS t2;
DROP TEMPORARY TABLE IF EXISTS tmp;
CREATE TEMPORARY TABLE t1 (
a INT(11)
);
CREATE TEMPORARY TABLE t2 (
b INT(11)
);
INSERT INTO t1 VALUES (1), (2), (3);
INSERT INTO t2 VALUES (4), (5), (6);
CREATE TEMPORARY TABLE tmp
SELECT
b AS f
FROM t2
UNION SELECT
a AS f
FROM t1
ORDER BY f;
SELECT * FROM tmp;
returns
f
=
1
2
3
4
5
6

Have you tried using a view? This way, you can use the UNION as simendsjo suggested and everything is in a single table. This is not exactly a temporary solution but a very nice, clean and efficient way of doing this.

I endeed up solving by using simendsjo's tips and used UNION ALL
<?php
$query = "SELECT `TALKING_TO` FROM `nnn_instant_messaging` WHERE `AUTHOR` = '" . DISPLAY_NAME . "' AND `TALKING_TO` != ''";
$query = mysql_query( $query, $CON ) or die( "_error_ " . mysql_error());
if( mysql_num_rows( $query ) != 0 ) {
while( $row = mysql_fetch_array( $query ) ) {
$table_str = 'SELECT REF, ACTION, TIME_STAMP, DATA, IMAGE, DISPLAY_NAME FROM actvbiz_networks.' . $row['TALKING_TO'] . ' UNION ALL ';
}
}else{
$table_str = "";
}
$table_str = $table_str . 'SELECT REF, ACTION, TIME_STAMP, DATA, IMAGE, DISPLAY_NAME FROM actvbiz_networks.' . DISPLAY_NAME . ' ORDER BY TIME_STAMP DESC';
$query = mysql_query( $table_str, $CON ) or die( "_error_ " . mysql_error());
if( mysql_num_rows( $query ) != 0 ) {
while( $rows = mysql_fetch_array( $query ) ) {

Related

Mysql - Get data from two tables

I have two tables webadstats and webstatsclick and i want to make below query from these two tables.
$sql2 = "SELECT
count(*) as 'impressions',
unix_timestamp(date(from_unixtime(A.time))) as 'timestamp',
COUNT(B.click) as 'clickss'
FROM `webadstats` as A
LEFT JOIN `webstatsclick` as B
ON A.pubadhash = B.pubadhash
WHERE A.pubadhash='$pubadhash'
GROUP BY date(from_unixtime(A.time))";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
while($row = mysqli_fetch_assoc($result2)) {
$impressions[] = $row['impressions'];
$clicksall[] = $row['clickss'];
$timestamp[] = $row['timestamp'];
}
for($i=0; $i<count($clicksall); $i++){
$str .= $timestamp[$i] . '||' . $impressions[$i] . '||' . $clicksall[$i] ."\n";
}
}
echo $str;
But the problem is that this query is generating same values for both the variables impressions and clickss out of which value of impressions variable is correct.
1542434400||1270||1270
1542520800||1800||1800
1542607200||1745||1745
1542693600||1805||1805
1542780000||1615||1615
1542866400||1740||1740
1542952800||1740||1740
1543039200||1830||1830
1543125600||1830||1830
1543212000||1615||1615
1543298400||1880||1880
1543384800||2125||2125
1543471200||1530||1530
1543557600||1370||1370
1543644000||120||120
My both the DB structure is
webadstats db
webadstats db
webstatsclick db
webstatsclick db
Kindly help me where i am wrong.
Let's go back to the two query approach. The problem is, we've been trying to use JOIN on pubadhash but also WHERE with pubadhash, so the values get multiplied.
$sql2 = "SELECT
count(*) as 'impressions',
unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webadstats`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";
$sql3 = "SELECT
count(*) as 'clickss',
unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webstatsclick`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
while($row = mysqli_fetch_assoc($result2)) {
$arr[$row['timestamp']]['impressions'] = $row['impressions'];
$arr[$row['timestamp']]['timestamp'] = $row['timestamp'];
$arr[$row['timestamp']]['clickss'] = 0;
}
$result3 = mysqli_query($conn, $sql3);
if (mysqli_num_rows($result3)>0) {
while($row = mysqli_fetch_assoc($result3)) {
$arr[$row['timestamp']]['clickss'] = $row['clickss'];
}
}
foreach($arr as $clicks){
$str .= $clicks['timestamp'] . '||' . $clicks['impressions'] . '||' . $clicks['clickss'] ."\n";
}
}
echo $str;

Why doesn't this SQL command work?

I cannot figure out why this sql query isn't working and why it doesn't filter by the keyword coming from URL.
Here is my code:
include("menujednoty.php");
$hostname="localhost";
$username="kintrogorgo";
$password="password";
$keyword = $_GET['a.tovar'];
$db = "jednoty";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query ('SELECT a.tovar ,
( select sum(b.kusy) from jednotypredaj as b where b.tovar=a.tovar and b.co="prijem" ) as prijem_ks,
( select sum(c.kusy) from jednotypredaj as c where c.tovar=a.tovar and c.co="predaj" ) as predaj_ks, kod
FROM jednotypredaj WHERE
(a.tovar LIKE '%$keyword%' ) as a GROUP BY a.tovar ORDER by a.tovar ASC') as $row)
{
echo "<tr>";
echo "<td>" . $row['tovar'] . "</td>";
echo "<td>" . $row['prijem_ks']. "</td>"; //Tu by mali bit predane kusy
echo "<td>" . $row['predaj_ks'] . "</td>";
echo "<td>" . $row['kod'] . "</td>";
echo "<td>" . ($row['predaj_ks']-$row['prijem_ks'] . "</td>");
echo "<td>" . (100/$row['prijem_ks']*$row['predaj_ks'] . "</td>");
echo '<td>ZobraziƄ</td>';
//echo '<td>In Development</td>';
//echo '<td>In Development 2</td>';
The quotes are breaking the SQL syntax, rewrite as a prepared statement to make it easier:
$stmt = $dbh->prepare('SELECT a.tovar ,
( select sum(b.kusy) from jednotypredaj as b
where b.tovar=a.tovar and b.co=:received ) as prijem_ks,
( select sum(c.kusy) from jednotypredaj as c
where c.tovar=a.tovar and c.co=:paid ) as predaj_ks, kod
FROM jednotypredaj WHERE
(a.tovar LIKE :keyword ) as a
GROUP BY a.tovar ORDER by a.tovar ASC');
$stmt->execute(array('received' => 'prijem','paid' => 'predaj','keyword' => $keyword));
foreach ($stmt as $row) {
echo "<tr>";
echo "<td>" . $row['tovar'] . "</td>";
...
Reconsider your SQL statement as you can either run correlated subqueries or conditional aggregates. Also, you table alias, a, was incorrectly positioned after WHERE clause:
Correlated subqueries (retains unit level records with kod column)
SELECT a.tovar,
(select sum(b.kusy) from jednotypredaj as b
where b.tovar=a.tovar and b.co='prijem') as prijem_ks,
(select sum(c.kusy) from jednotypredaj as c
where c.tovar=a.tovar and c.co='predaj') as predaj_ks,
a.kod
FROM jednotypredaj as a
WHERE (a.tovar LIKE '%$keyword%')
ORDER by a.tovar ASC
Conditional aggregates (group by aggregate records w/o kod unless added as a group)
SELECT a.tovar,
SUM(CASE WHEN a.co='prijem' THEN a.kusy ELSE NULL END) as prijem_ks,
SUM(CASE WHEN a.co='predaj' THEN a.kusy ELSE NULL END) as predaj_ks
FROM jednotypredaj as a
WHERE (a.tovar LIKE '%$keyword%')
GROUP BY a.tovar
ORDER by a.tovar ASC
MySQL may allow kod in SELECT clause and not in GROUP BY clause of aggregate query if your instance has the ONLY_FULL_GROUP_BY setting turned off but is not recommended and not ANSI-SQL compliant.
And as mentioned parameterize these queries in PHP script, binding string literals, that helps avoid quote handling and SQL injection.

mysql query - to echo groups of products with foreach in stylable divs

hope somone can help me - I have this code:
$query = "SELECT * FROM `products` WHERE `category` = 100 AND `showme` = 1 `ORDER BY `nr` ASC";`
$result = mysql_query($query);
while($row = mysql_fetch_object($result)){
echo '<div class="'.$row->design.'">
<img src="'.$row->img.'" width="100%"><br>
<span><b>'.$row->name.'</b></span><br><span>'.$row->descr.'</span><br />
<span>'.$row->preprice.' </span><span>'.$row->price.'</span><span> '.$row->unit.'</span></div>
';
}
It displays like this: http://gartenundhof.de/gartenundhof-produkte5.php
It should look about like:http://gartenundhof.de/gartenundhof-produkte.php (which has 3 separate queries)
"SELECT * FROM 'products' ORDER BY 'category' ASC";
Try this
You can try it:
$query = "SELECT * FROM `products` WHERE `showme` = 1 `ORDER BY category,`nr` ASC";
$result = mysql_query($query);
$category = -1;
while($row = mysql_fetch_object($result)){
if($category != $row->category) {
$category = $row->category;
eho "<h2>$category</h2>";
}
echo '<div class="'.$row->design.'">
<img src="'.$row->img.'" width="100%"><br>
<span><b>'.$row->name.'</b></span><br><span>'.$row->descr.'</span><br />
<span>'.$row->preprice.' </span><span>'.$row->price.'</span><span> '.$row->unit.'</span></div>';
}
Assuming you have 2 tables Products and Categories:
$categories_query = "SELECT * FROM categories ORDER BY id ASC";
$categories = mysql_query($categories_query);
while($category = mysql_fetch_object($categories)) {
echo "Category: " . $category->name . "<br />";
$products_query = "SELECT * FROM products WHERE category_id = " . $category->id . " AND showme = 1 ORDER BY nr ASC";
while($product = mysql_fetch_object($products_query)) {
echo "Product: " . $product->name . "<br />";
}
}

dynamic sql UPDATE query

How can I update a table in the data base where the SET clause from MySQL query depends on variables? It can be one $var, two, or many more.
Here is my ex. code:
$name = 'comp_name = "'.$nume.'",';
$large = 'logolarge = "'.$linklogolarge.'",';
$small = 'logosmall = "'.$linklogosmall.'",';
...............................
$sql = 'UPDATE company
SET
'.$name.'
'.$large.'
'.$small.'
WHERE id_comp = 43 ';
The problem is that the normal syntax of the UPDATE query is that after SET .......between values needs a comma " , "
ex.
UPDATE table
SET
col1 = x ,
col2 = y ,
col3 = z
WHERE id = 4
and at the end before WHERE doesn't needs one ..... ( ex. after " z ")
So how can I make the sql query to accept different combination of those $var ...( only '.$name.' or '.$name.' and '.$large.' or only last two '.$large.' and '.$small.' .... etc)
basically any combination between those 3 var ...and maybe combining more than 3 var.
$name = "comp_name = '$nume'";
$large = "logolarge = '$linklogolarge'";
$small = "logosmall = '$linklogosmall'";
$sql = "UPDATE company SET " . $name;
if( ! is_null( $linklogolarge ) ) $sql = $sql . ", " . $large;
if( ! is_null( $linklogosmall ) ) $sql = $sql . ", " . $small;
$where = " WHERE id_comp = 43"; /* change this if required*/
$sql = $sql . $where;
echo $sql;

Head busting MYSQL error 1064 What's Wrong with my Syntax? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I've been staring at this for a moment and think I'm not perceiving the obvious.
The resulting display is 1064 (mysql reference says it's a syntax error)
$query = "INSERT INTO members ( id , username , password , all , articles ) VALUES ( ";
$query .= "'' , " ;
$query .= $username . "' , '" ;
$query .= $password . "' , '" ;
$query .= $allVals . "' , ";
$query .= "'' );";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)){
echo mysqli_errno($con);
echo mysqli_connect_error($con);
}
I should note that $allVals is an encoded json object.
What's wrong with my query?
$query .= "'' , " ;
You miss here a single-quote.
$query .= "'' , '" ;
Should do the job.
I'd also consider to use prepared statements to better see where your syntax error may be; when you try to build your query like this, is will be probably more difficult to debug it.
$stmt = $con->prepare("INSERT INTO members ( id , username , password , all , articles ) VALUES ( '', ?, ?, ?, '')");
$stmt->bind_param("sss", $username, $password, $allVals);
$stmt->execute();
/* ... */
It looks like there is a single quote after $username, but not before:
$query = "INSERT INTO members ( id , username , password , all , articles ) VALUES ( ";
$query .= "'' , '" ; //missed the quote here
$query .= $username . "' , '" ;
$query .= $password . "' , '" ;
$query .= $allVals . "' , ";
$query .= "'' );";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)){
echo mysqli_errno($con);
echo mysqli_connect_error($con);
}
You must put common after every values.
$query = "INSERT INTO members ( id , username , password , all , articles ) VALUES ( ";
$query .= "'' , '" ;
$query .= $username . "','" ;
$query .= $password . "', '" ;
$query .= $allVals . "' ";
$query .= ")";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)){
echo mysqli_errno($con);
echo mysqli_connect_error($con);
}
If you aren't inserting data into id or articles columns, don't include them as part of your query statement:
$query = "INSERT INTO members ( username , password , all ) VALUES ( '";
$query .= $username . "' , '" ;
$query .= $password . "' , '" ;
$query .= $allVals . "' );";
$result = mysqli_query($con, $query);
if (mysqli_errno($con)){
echo mysqli_errno($con);
echo mysqli_connect_error($con);
}
Additionally, you need to make sure your variables are properly escaped.
I like doing it this way:
$query .= "('' , '".$username . "' , '" .$password . "' , '".$allVals . "' ,'' )";
It also lends itself to things like inserting multiple rows :
$qvals[] = "('' , '".$username[1] . "' , '" .$password[1] . "' , '".$allVals[1] . "' ,'' )";
$qvals[] = "('' , '".$username[2] . "' , '" .$password[2] . "' , '".$allVals[2] . "' ,'' )";
$qvals[] = "('' , '".$username[3] . "' , '" .$password[3] . "' , '".$allVals[3] . "' ,'' )";
$query = "INSERT INTO members ( `id` , `username` , `password` , `all` , `articles` ) VALUES ".implode(',',$qvals);
You can double check the result by checking what echo $query; outputs.