I'm trying to add the articles id to the title, summary and content but I don't know how to do it can some one help me solve this problem.
Here is the code that is giving me the problem.
while($row = mysqli_fetch_assoc($run)) {
$id[] = $row['id'];
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
}
And here is my PHP and MySQL code in full below.
$x = 0;
$con = null;
$search = $_REQUEST['search'];
$id = array();
$title = array();
$summary = array();
$content = array();
$search_explode = mysqli_real_escape_string($dbc, $search);
$search_explode = explode(' ', $search_explode);
foreach($search_explode as $search_each) {
$x++;
if($x == 1){
$con .= " article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
} else {
$con .= " OR article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
}
}
$con = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE ($con)
AND users.active IS NULL
AND users.deletion = 0";
$run = mysqli_query($dbc, $con);
$search_term = mysqli_num_rows($run);
while($row = mysqli_fetch_assoc($run)) {
$id[] = $row['id'];
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
}
while($row = mysqli_fetch_assoc($run)) {
// $id[] = $row['id']; you probably do not need this anymore
$title[$row['id']] = $row['title'];
$summary[$row['id']] = $row['summary'];
$content[$row['id']] = $row['article_content'];
}
// at this point, each array will contain rows
// with keys matching the corresponding id
var_dump($title);
var_dump($summary);
var_dump($content);
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
mysqli_fetch_assoc will fetch an associated array. Accessing the data directly like so $row['summary'] should fix your problem.
EDIT
Are you talking about string concatenation?
$title[] = $row['id'] . ' ' . $row['title'];
$summary[] = $row['id'] . ' ' . $row['summary'];
$content[] = $row['id'] . ' ' . $row['article_content'];
The above code will basically append the title/summary/content to your article ID and add it into respective arrays.
I am not sure what you want to achieve but I would suggest the the following solution. Please take a look.
CREATE TABLE IF NOT EXISTS users (
user_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
deletion int(11) NOT NULL DEFAULT '0',
active int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table users
INSERT INTO users (user_id, name, deletion, active) VALUES
(1, 'John', 0, 1),
(2, 'George', 0, 1);
--
-- Table structure for table users_articles
CREATE TABLE IF NOT EXISTS users_articles (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) NOT NULL,
article_content varchar(255) NOT NULL,
title varchar(255) NOT NULL,
summary text NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table users_articles
INSERT INTO users_articles (id, user_id, article_content, title, summary) VALUES
(1, 1, 'test', 'test', 'test test test test'),
(2, 2, 'test 2', 'test 2', 'test test'),
(3, 1, 'test 3', 'test 3 ', 'test test test test 3'),
(4, 2, 'test 3', 'test 3', 'test test 3');
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqli = new mysqli("localhost", "root", "", "articles");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
$con = 1;
$sql = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE ($con)
AND users.active = 1
AND users.deletion = 0";
$results = array();
if ($result = $mysqli->query($sql)) {
printf("Select returned %d rows.\n", $result->num_rows);
print '<pre>';
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
print_r($results);
print '</pre>';
/* free result set */
$result->close();
}
$mysqli->close();
?>
and when you will iterate $results you can concatenate id and other fields in that case you can utilize the result array in other areas too.
Related
How can I make if player X has the same number of points as any other player, so that it displays them in 1 row?
table users:
`uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(120) NOT NULL DEFAULT '',
`points_first` int(11) NOT NULL DEFAULT 0,
`points_second` int(11) NOT NULL DEFAULT 0,
My Query:
SELECT uid, username, points_first, points_second
FROM users
LIMIT 5
Results:
PHP to sort data DESC and display using templates:
$query = $db->query('SELECT uid, username, points_first, points_second FROM users');
$no = $noFirst = $noSecond = 0;
$dataFirstPoints = $dataSecondPoints = [];
$i = 0;
while($row = $db->fetch_array($query)){
if($row['points_first'] != 0){
$dataFirstPoints[$i]['points'] = $row['points_first'];
$dataFirstPoints[$i]['username'] = $row['username'];
}
if($row['points_second'] != 0){
$dataSecondPoints[$i]['points'] = $row['points_second'];
$dataSecondPoints[$i]['username'] = $row['username'];
}
$i++;
if($row['points_second'] === 0) $firstRows = "<div class=\"nodata\">No Data</div>";
if($row['points_first'] === 0) $secondRows = "<div class=\"nodata\">No Data</div>";
}
arsort($dataFirstPoints);
arsort($dataSecondPoints);
foreach($dataFirstPoints as $data){
$points = $data['points'];
$noFirst++;
$no = $noFirst;
eval("\$secondRows .= \"".$templates->get("rows")."\";");
}
foreach($dataSecondPoints as $key => $data){
$points = $data['points'];
$noSecond++;
$no = $noSecond;
eval("\$firstRows .= \"".$templates->get("rows")."\";");
}
eval("\$main = \"".$templates->get("main")."\";");
Results from PHP and templates:
Now we can see that two users have points in the same category (points_first).
How can I do to get this effect? What to use?:
Group the results by the points and use GROUP_CONCAT to concatenate the usernames.
SELECT points_first, GROUP_CONCAT(username SEPARATOR ', ') AS users FROM users GROUP BY points_first ORDER BY points_first DESC;
I hope it is helpful!
I am trying to insert PHP variables in a mysql table, where the table name is also a variable, using mysqli_query. I've tried multiple solutions from stackoverflow but it still does not work.
I try to do it like this, maybe I am missing something. Thank you in advance!
<?php
session_start();
#include_once "modules/connections/dbconn.php";
$value = $_POST['value'];
$playerid = $_SESSION["steamid"];
$playername = fetchinfo("name","users","steamid",$playerid);
$playeravatar = fetchinfo("avatar","users","steamid",$playerid);
$playercoins = fetchinfo("coins", "users","steamid",$playerid);
if($playercoins - $value < 0){
die(json_encode(array('message' => 'ERROR', 'code' => "Not enough coins!")));
}
$game = fetchinfo("value","parameters","name","raffleRound");
$maxitems = fetchinfo("value","parameters","name","raffleMaxritems");
$items = fetchinfo("itemsnum","rafflegames","id",$game);
$itemname = "Coins";
$itemavatar = "images/creditcardicon.png";
$color = "D2D2D2";
$initialvalue = fetchinfo("value","rafflegames","id",$game);
$from = $initialvalue * 100;
$to = $from + $value * 100;
$tablename = 'rafflegame'.$game;
if($items < $maxitems){
mysqli_query($GLOBALS["connect"], "UPDATE rafflegames SET `value`=`value`+$value, `itemsnum`=`itemsnum`+1 WHERE `id`=$game");
mysqli_query($GLOBALS["connect"], "UPDATE users SET `coins`=`coins`-$value WHERE `steamid`=$playerid");
mysqli_query($GLOBALS["connect"], "INSERT INTO `" . $tablename . "` VALUES ('".$playerid."', '".$playername."','".$itemname."','".$color."','".$value."','".$playeravatar."','".$itemavatar."','".$from."','".$to."')");
}
else {
die(json_encode(array('message' => 'ERROR', 'code' => "Too many items in the current game")));
}
?>
The other two queries work just fine.
The table structure is this:
mysqli_query($GLOBALS['connect'],"CREATE TABLE `rafflegame$roundNumber` (
`id` int(11) NOT NULL auto_increment,
`userid` varchar(70) NOT NULL,
`username` varchar(70) NOT NULL,
`item` text,
`color` text,
`value` float,
`avatar` varchar(512) NOT NULL,
`image` text NOT NULL,
`from` int NOT NULL,
`to` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
mysqli_query($GLOBALS['connect'],"TRUNCATE TABLE `rafflegame$roundNumber`");
There is difference between table structure and insert column coumnt, When you want id column as auto incremented in that case column name should be included in insert query.
Please use the code as below:
<?php
session_start();
#include_once "modules/connections/dbconn.php";
$value = $_POST['value'];
$playerid = $_SESSION["steamid"];
$playername = fetchinfo("name","users","steamid",$playerid);
$playeravatar = fetchinfo("avatar","users","steamid",$playerid);
$playercoins = fetchinfo("coins", "users","steamid",$playerid);
if($playercoins - $value < 0){
die(json_encode(array('message' => 'ERROR', 'code' => "Not enough coins!")));
}
$game = fetchinfo("value","parameters","name","raffleRound");
$maxitems = fetchinfo("value","parameters","name","raffleMaxritems");
$items = fetchinfo("itemsnum","rafflegames","id",$game);
$itemname = "Coins";
$itemavatar = "images/creditcardicon.png";
$color = "D2D2D2";
$initialvalue = fetchinfo("value","rafflegames","id",$game);
$from = $initialvalue * 100;
$to = $from + $value * 100;
$tablename = 'rafflegame'.$game;
if($items < $maxitems){
mysqli_query($GLOBALS["connect"], "UPDATE rafflegames SET `value`=`value`+$value, `itemsnum`=`itemsnum`+1 WHERE `id`=$game");
mysqli_query($GLOBALS["connect"], "UPDATE users SET `coins`=`coins`-$value WHERE `steamid`=$playerid");
mysqli_query($GLOBALS["connect"], "INSERT INTO `" . $tablename . "`(`userid`,`username`,`item`,`color`,`value`,`avatar`,`image`,`from`,`to`) VALUES ('".$playerid."', '".$playername."','".$itemname."','".$color."','".$value."','".$playeravatar."','".$itemavatar."','".$from."','".$to."')");
}
else {
die(json_encode(array('message' => 'ERROR', 'code' => "Too many items in the current game")));
}
?>
i have make its here before. mySQL - how to show all records from the messages table, not just one
Hello
This is how I'm going to build a messaging system which make the user 1 and user 2 has a conversation somewhere.
That itself, I go to the site so come all the conversations appear on the page.
the problem is such that it does only one message from the database. Therefore, I would like it to display all messages from the database.
Database
CREATE TABLE IF NOT EXISTS `fms_opslagpm` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fra_id` int(11) NOT NULL,
`til_id` int(11) NOT NULL,
`title` varchar(30) NOT NULL,
`besked` longtext NOT NULL,
`datotid` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `fms_opslagpm` (`id`, `fra_id`, `til_id`, `title`, `besked`, `datotid`) VALUES
(1, 2, 1, 'hrerherhe', 'hello world ', '2014-04-01 22:25:29'),
(2, 2, 1, 'hrerherhe', 'hej', '2014-04-01 23:51:49');
mysqli/php here.
$sql = "
SELECT fms_bruger.fornavn, fms_bruger.efternavn, fms_opslagpm.id, fms_opslagpm.fra_id, fms_opslagpm.til_id, fms_opslagpm.title, fms_opslagpm.besked
FROM fms_bruger INNER JOIN fms_opslagpm ON fms_bruger.id=fms_opslagpm.fra_id
WHERE fms_opslagpm.id = ? and fms_opslagpm.fra_id = ? OR fms_opslagpm.til_id = ?
GROUP BY fms_opslagpm.title ORDER BY fms_opslagpm.datotid DESC
";
if ($stmt = $this->mysqli->prepare($sql)) {
$stmt->bind_param('iii', $id, $fra_id, $til_id);
$id = $_GET["id"];
$fra_id = $_SESSION["id"];
$til_id = $_SESSION["id"];
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($fornavn, $efternavn, $id, $fra_id, $til_id, $title, $besked);
while ($stmt->fetch()) {
?>
<tr class="postbox">
<td class="beskedinfoBOX">
<p>
<?php
echo $fornavn . " " . $efternavn;
?>
</p>
</td>
<td>
<?php
//beskeden.
echo $besked;
?>
</td>
</tr>
<?php
}
$stmt->close();
}
else
{
echo 'Der opstod en fejl i erklæringen: ' . $this->mysqli->error;
}
This is how when I write fra_id = 2 and til_id = 1, then shows it is still only the content of the page. So samtidigvæk a message on the page.
fms_opslagpm = fra_id - is he / she who sends the message
fms_opslagpm = til_id - is he / she who receives the message
Your issue is that you are selecting only
WHERE fms_opslagpm.id = ?
So it will only return 1 row where there is an exact match on the id. It looks like you where trying to also select the rows that have the same title as the row with the id
GROUP BY fms_opslagpm.title
but even if you returned more than 1 row, this would have collapsed the results into 1 row again.
You need to change your query to get the title of the row WHERE fms_opslagpm.id = ?, and using OR select all the other rows with the same title.
Try -
SELECT
fms_bruger.fornavn,
fms_bruger.efternavn,
fms_opslagpm.id,
fms_opslagpm.title,
fms_opslagpm.besked
FROM fms_bruger
INNER JOIN fms_opslagpm ON fms_bruger.id=fms_opslagpm.fra_id
WHERE (
fms_opslagpm.id = ?
OR fms_opslagpm.title = (
SELECT fms_opslagpm.title
FROM fms_opslagpm
WHERE fms_opslagpm.id = ?
)
)
AND
(
fms_opslagpm.fra_id = ?
OR
fms_opslagpm.til_id = ?
)
ORDER BY fms_opslagpm.datotid DESC
See this SQLFiddle example - http://sqlfiddle.com/#!2/36d534/6
You will also need to include 1 more param to your bind_param
$stmt->bind_param('iiii', $id, $id1, $fra_id, $til_id);
$id = $_GET["id"];
$id1 = $_GET["id"];
$fra_id = $_SESSION["id"];
$til_id = $_SESSION["id"];
can anyone help? my code doesn't seem to store the value of product id here in my code have a look I am also getting the ID from another table
<?php
include("Connection.php");
$dTime = time();
$myValue = $_REQUEST['dValue'];
echo "<p>
The time is: {$dTime}<br/>
The choice is {$myValue}
</p>
";
$sql = "Select ID from product where NAME = '$myValue'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
$pid=$row["PRODUCT_ID"];
$sql2 = "INSERT INTO `starbucks`.`order_details` (
`ID` ,
`ORDER_ID` ,
`PRODUCT_ID` ,
`QTY`
)
VALUES (
NULL , '', '$pid', '1'
)";
$result2 = mysql_query($sql2);
?>
updated the code
$id = $row["ID"]
instead of:
$id = $row;
You have an incorrect array value for $id instead of the array's ID key:
$id = $row;
// Should be
$id = $row['ID'];
in your original code there is no error handling,you should do something like this:
$sql = "Select ID from product where NAME = '$myValue'";
if ($sql) {
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
$pid = $row["PRODUCT_ID"];
$sql2 = "INSERT INTO `starbucks`.`order_details` (
`ID` ,
`ORDER_ID` ,
`PRODUCT_ID` ,
`QTY`
)
VALUES (
NULL , '', '$pid', '1'
)";
$result2 = mysql_query($sql2);
if (!$result2) {
echo mysql_error();
break;
}
} else {
echo mysql_error();
}
And see what error you get.
I am trying to create a category menu with sub categories. I have the following MySQL table:
--
-- Table structure for table `categories`
--
CREATE TABLE IF NOT EXISTS `categories` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(1000) NOT NULL,
`slug` varchar(1000) NOT NULL,
`parent` int(11) NOT NULL,
`type` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=66 ;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`ID`, `name`, `slug`, `parent`, `type`) VALUES
(63, 'Party', '/category/party/', 0, ''),
(62, 'Kitchen', '/category/kitchen/', 61, 'sub'),
(59, 'Animals', '/category/animals/', 0, ''),
(64, 'Pets', '/category/pets/', 59, 'sub'),
(61, 'Rooms', '/category/rooms/', 0, ''),
(65, 'Zoo Creatures', '/category/zoo-creatures/', 59, 'sub');
And the following PHP:
<?php
include("connect.php");
echo "<ul>";
$query = mysql_query("SELECT * FROM categories");
while ($row = mysql_fetch_assoc($query)) {
$catId = $row['id'];
$catName = $row['name'];
$catSlug = $row['slug'];
$parent = $row['parent'];
$type = $row['type'];
if ($type == "sub") {
$select = mysql_query("SELECT name FROM categories WHERE ID = $parent");
while ($row = mysql_fetch_assoc($select)) {
$parentName = $row['name'];
}
echo "<li>$parentName >> $catName</li>";
}
else if ($type == "") {
echo "<li>$catName</li>";
}
}
echo "</ul>";
?>
Now Here's the Problem,
It displays this:
* Party
* Rooms >> Kitchen
* Animals
* Animals >> Pets
* Rooms
* Animals >> Zoo Creatures
I want it to display this:
* Party
* Rooms >> Kitchen
* Animals >> Pets >> Zoo Creatures
Is there something wrong with my loop? I just can't figure it out.
Both 'Zoo Creatures' and 'Pets' have 'Animals' (59) as their parent.
To do what you want you probably need to set 'Pets' as a parent for 'Zoo Creatures'.
To do that replace last SQL line with this:
(65, 'Zoo Creatures', '/category/zoo-creatures/', 64, 'sub');
echo '<ul>';
$parents = mysql_query('SELECT * FROM categories WHERE parent = 0');
while ($row = mysql_fetch_assoc($parents)) {
$catId = $row['ID'];
$catName = $row['name'];
$catSlug = $row['slug'];
$parent = $row['parent'];
$type = $row['type'];
$output = "<li>$catName";
$children = mysql_query("SELECT name FROM categories WHERE parent = $catId");
while ($child = mysql_fetch_assoc($children)) {
$childName = $child['name'];
$output .= " >> $childName";
}
$output .= '</li>';
echo $output;
}
echo '</ul>';
Change your first select statement to:
SELECT * FROM categories WHERE parent = 0
You'll also need to recursively call the code in your $type == "sub" code.
Your type field appears to duplicate the functionality of the parent field. If the menu item has a parent, is not a submenu?