Condensing this code - php

I have the following code I want to run, but the problem is $this->type is set when the class is created by specifying either petition, proposal, or amendment. As you can see my $sql statement is a UNION of all three, and I want to specify which table (pet,prop,or amend) each row of data comes from.
public function userProposals() {
$username = User::getUsername();
$sql = "SELECT * FROM petition WHERE author = '$username'
UNION SELECT * FROM proposition WHERE author = '$username'
UNION SELECT * FROM amendment WHERE author = '$username'";
$query = mysql_query($sql);
$state = User::userState();
while ($row = mysql_fetch_assoc($query)) { // $this->type needs to specify pet,prop,amend
echo "
<tr>
<td>$row[id]</td>
<td><a href='viewproposal.php?type=$this->type&id=$row[id]'>$row[title]</a></td>
<td>$this->type</td>
<td>$state</td>
</tr>";
}
}
As you can see, $this->type will only say one of the three. To get my function work how i wanted to, I did this (which I feel is too long & there must be a shorter way).
public function userProposals() {
$username = User::getUsername();
$state = User::userState();
$sql = "SELECT * FROM petition WHERE author = '$username'";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
echo "
<tr>
<td>$row[id]</td>
<td><a href='viewproposal.php?type=petition&id=$row[id]'>$row[title]</a></td>
<td>Petition</td>
<td>$state</td>
</tr>";
}
$sql = "SELECT * FROM proposition WHERE author = '$username'";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
echo "
<tr>
<td>$row[id]</td>
<td><a href='viewproposal.php?type=proposition&id=$row[id]'>$row[title]</a></td>
<td>Proposition</td>
<td>$state</td>
</tr>";
}
$sql = "SELECT * FROM amendment WHERE author = '$username'";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
echo "
<tr>
<td>$row[id]</td>
<td><a href='viewproposal.php?type=amendment&id=$row[id]'>$row[title]</a></td>
<td>Amendment</td>
<td>$state</td>
</tr>";
}
}

I would normally do something like the following:
public function userProposals() {
$username = User::getUsername();
$state = User::userState();
$tables = array('petition', 'proposition', 'amendment');
foreach($tables as $table) {
$label = ucwords($table);
$sql = "SELECT * FROM $table WHERE author = '" . mysql_real_escape_string($username) . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
echo "
<tr>
<td>$row[id]</td>
<td><a href='viewproposal.php?type=$table&id=$row[id]'>$row[title]</a></td>
<td>$label</td>
<td>$state</td>
</tr>";
}
}
}

Why don't you try the modified SQL:
SELECT 'petition' as typ,title,id FROM petition
WHERE author = '$username'
UNION SELECT 'proposition' as typ,title,id FROM proposition
WHERE author = '$username'
UNION SELECT 'amendment' as typ,totle,id FROM amendment
WHERE author = '$username'"
and then use the typ from each returned row ($row[typ]) instead of $this->type?
The whole thing should be:
public function userProposals() {
$username = User::getUsername();
$sql = "SELECT 'petition' as typ,id,title FROM petition
WHERE author = '$username'
UNION SELECT 'proposition' as typ,id,title FROM proposition
WHERE author = '$username'
UNION SELECT 'amendment' as typ,id,title FROM amendment
WHERE author = '$username'"
$query = mysql_query($sql);
$state = User::userState();
while ($row = mysql_fetch_assoc($query)) {
echo "<tr>
<td>$row[id]</td>
<td><a href='viewproposal.php?type=$row[typ]&id=$row[id]'>
$row[title]
</a></td>
<td>$row[typ]</td>
<td>$state</td>
</tr>";
}
}
based on what was in your question.

Related

Show different data in webpage when clicked depending on the ID

I am trying to show user data when clicking link depending on a story ID. However, the page is showing the same data from one row in the database every time (web link is showing a different ID 'php?story_id=10' etc. but it's still showing the same data.
I have this function:
function displayStories(){
include('conn/conn.php');
$queryread = "SELECT Users.ID, Users.FirstName, Stories.Age, Stories.Story,
Stories.Image FROM `Stories` INNER JOIN `Users` ON Users.ID = Stories.User_ID";
$result = mysqli_query($conn, $queryread) or die(mysqli_error($conn));
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_assoc($result)){
$name = $row["FirstName"];
$idData = $row["ID"];
$age = $row["Age"];
$story = $row["Story"];
$limit = mb_strimwidth($story, 0, 300, "...");
echo
"<div class='stories'>
<a href='storyDis.php?story_id=$idData'>
<h5><b>$name</b></h5></a>
<p><b>$age years old</b></p>
<p>$limit</p>
</div>
";
}
}
mysqli_close($conn);
}
And this to query to display the data(variables called in HTML):
include('conn/conn.php');
$str = htmlentities($_GET["story_id"]);
$query = "SELECT * "
. "FROM Stories "
. "WHERE ID='$str'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$queryread = "SELECT Users.FirstName, Stories.Age, Stories.Story,
Stories.Image FROM `Stories` INNER JOIN `Users` ON Users.ID = Stories.User_ID";
$result1 = mysqli_query($conn, $queryread) or die(mysqli_error($conn));
if(mysqli_num_rows($result1) > 0 ){
while($row = mysqli_fetch_assoc($result1)){
$name = $row["FirstName"];
$age = $row["Age"];
$story = $row["Story"];
$image = $row["Image"];
}
}
mysqli_close($conn);
?>
EDIT
Had two queries when I only needed one.
$str = htmlentities($_GET["story_id"]);
$queryread = "SELECT Stories.ID, Users.FirstName, Stories.Age, Stories.Story, Stories.Image FROM `Stories` INNER JOIN `Users` ON Users.ID = Stories.User_ID
WHERE Stories.ID='$str'";
$result1 = mysqli_query($conn, $queryread) or die(mysqli_error($conn));
if(mysqli_num_rows($result1) > 0 ){
while($row = mysqli_fetch_assoc($result1)){
$name = $row["FirstName"];
$age = $row["Age"];
$story = $row["Story"];
$image = $row["Image"];
}
}
mysqli_close($conn);
?>
you are reading the data from (result1) not from (result).
Change this one while($row = mysqli_fetch_assoc($result1)){
to
while($row = mysqli_fetch_assoc($result)){
and then it will works fine with you .

SELECT 2 Identical databases to get 2 website orders on one list

I'm trying to connect two databases into a mysql query and it's also great!
After that, I try to find data on the order in the correct database to get meta_value from it.
But it mixes meta_value $ first name and sometimes duplicates them on the rows.
If I just conect 1 database, they will come out as they should
Anybody can see what goes wrong?
Url to example: https:// http://kundeservice.coalsmile.com/test4.php
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$v1 = "coalsmil_wp282";
$v2 = "coalsmil_wp111";
$v3 = "coalsmil_wp72";
$v4 = "coalsmil_wp193";
$v5 = "coalsmil_wp555";
$v6 = "coalsmil_wp366";
$v7 = "coalsmil_wp74";
$v8 = "coalsmil_wp721";
$v9 = "coalsmil_wp924";
$v10 = "coalsmil_wp253";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//Here I connect to both databases
$query103 = mysqli_query($conn, "SELECT * FROM `$v1`.`wpd2_posts`
where post_status='wc-processing' or post_status='wc-completed'
or post_status='wc-failed' UNION
SELECT * FROM `$v2`.`wpd2_posts`
where post_status='wc-processing' or post_status='wc-completed'
or post_status='wc-failed' order by post_date DESC ") or die(mysqli_error($conn));
?>
<br>
<h2>Database 3</h2>
<table style="width: 100%">
<tr>
<td>ID</td>
<td>??</td>
<td>??</td>
<td>??</td>
<td>??</td>
<td>??</td>
</tr>
<?php
while($row = mysqli_fetch_array($query103))
{
// Here I try to find what database the customer is on
$id2 = $row['ID'];
if($row['ID'] == ''){
echo "intet id";
}else {
$query = mysqli_query($conn, "SELECT * FROM `$v1`.`wpd2_posts` where ID = '$id2' ORDER BY id") or die(mysqli_error($conn));
if(mysqli_num_rows($query) == '') {
$query = mysqli_query($conn, "SELECT * FROM `$v2`.`wpd2_posts` where ID = '$id2' ORDER BY id") or die(mysqli_error($conn));
if(mysqli_num_rows($query) == '') {
}else{
$version = "coalsmil_wp111";
}
}else{
$version = "coalsmil_wp282";
}
}
echo "<tr>";
echo "<td>". $row['ID']."</td>";
echo "<td>". $row['post_date']."</td>";
echo "<td>". $row['post_status']."</td>";
//And here I try to get the data out
$querynavn = mysqli_query($conn, "SELECT meta_value FROM `$version`.`wpd2_postmeta` where meta_key='_shipping_first_name' and post_id='$id2' ") or die(mysqli_error($conn));
while($row2 = mysqli_fetch_array($querynavn))
{
$fornavn = urldecode($row2['meta_value']);
}
echo "<td>". $fornavn."</td>";
echo "<td>".$version."</td>";
echo "<td>6</td>";
echo "</tr>";
}
?>
</table>
If you're connections are on the same database server you can specify the schema (database name) to select things from both over one connection. You do this by using schema_name.table_name instead of just the table's name.
So like:
SELECT * FROM schema_name.wpd2_posts WHERE ...
In your case you could use UNION to put it all together:
SELECT * FROM `schema1.wpd2_posts`
where post_status='wc-processing' or post_status='wc-completed'
or post_status='wc-failed' UNION
SELECT * FROM `schema2.wpd2_posts`
where post_status='wc-processing' or post_status='wc-completed'
or post_status='wc-failed' order by post_date DESC LIMIT 10
On a side note you could make this query a bit more readable by using the IN() clause for your critera:
WHERE post_status IN('wc-processing', 'wc-completed','wc-failed')

MySQL Multi Query store result second query

I am querying from two different tables in the database here and I can store the values from the first query but how do I store the information from the second query?
$query = "SELECT * ";
$query .= "FROM user_account ";
$query .= "WHERE user_id = $user_id ";
$query .= "SELECT * ";
$query .= "FROM user_profile ";
$query .= "WHERE user_id = $user_id ";
if (mysqli_multi_query($mysqli, $query)) {
do {
if ($result = mysqli_store_result($mysqli)) {
while ($row = mysqli_fetch_row($result)) {
$Firstname = $row['Firstname'];
$Lastname = $row['Lastname'];
$Email = $row['Email'];
$Birthday = $row['Birthday'];
$Address = $row['Address'];
$Zip = $row['Zip'];
$City = $row['City'];
$State = $row['State'];
$Country = $row['Country'];
$Avatar = $row['Avatar']; Will be added later
$Phone = $row['Phone'];
$Website = $row['Website'];
$Member_level = $row['Member_level'];
}
mysqli_free_result($result);
}
if (mysqli_more_results($mysqli)) {
}
while (mysqli_next_result($mysqli)) ;
}
}
Just the usual way
$query = "SELECT * FROM user_account WHERE user_id = $user_id ";
$account = $mysqli->query($query)->fetch_assoc();
$query = "SELECT * FROM user_profile WHERE user_id = $user_id ";
$profile = $mysqli->query($query)->fetch_assoc();
as simple as that.
I am really wondering why PHP users are inclined to writing SO MUCH code and to using so much intricate ways for the most trifle operations
On a side note, in your particular case you can write a single JOIN query.
In your code, why are you using mysqli_free_result function because it will frees the memory associated with a result object so when while loop run it will not show any result.
$query = "SELECT * FROM user_account WHERE user_id = $user_id ";
$query .= "SELECT * FROM user_profile WHERE user_id = $user_id ";
if (mysqli_multi_query($mysqli, $query)) {
do {
if ($result = mysqli_store_result($mysqli)) {
while ($row = mysqli_fetch_assoc($result)) {
var_dump($row); //for checking result
// Now use array to show your result
}
} }while (mysqli_next_result($mysqli)) ;
You should always free your result with mysqli_free_result(), when
your result object is not needed anymore.

How to connect php to navicat with 2 tables

$i = 1;
$sql = "
SELECT
heroes.char_id, characters.char_name, heroes.class_id, heroes.count,
heroes.played, heroes.active FROM heroes, characters
WHERE characters.obj_Id = heroes.char_id AND heroes.played = 1
";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query))
{
echo "
<tr>
<td><span id='lefttop'><b><font color='#007aa2'>".$i++." </font></td><td><b><font color='#f6ff00'>".$row['char_name']."</font></td></span><div style='float:right;'><td><b> ".$row['count']."</td></div> <br />
</tr>
";
}
echo "";
?>
Anyone can help? im trying to make a hero status script on a java server, and i need to connect into 2 tables which is "heroes"(this is where i get the hero) and "character" (this is where i get the hero names)
Try this Temple:
<?php
$sql1 = "SELECT * your table1";
$query1 = mysql_query($sql);
while($row1 = mysql_fetch_array($query1))
{
echo "<tr>";
$sql2 = "SELECT * your table2";
$query2 = mysql_query($sql2);
while($row2 = mysql_fetch_array($query2))
{
echo "<td>[yor Vars here]</td>";
}
echo "</tr>";
}
?>

SQL ERROR mysql_fetch_array(): not valid?

I just can't figure out why i get the error message, I have tried removing the'' and the()
I have run the script in phpmyadmin and it says the problem with my syntax is at $result = ("SELECT * FROM 'test_prefixCatagory' ORDER by 'Cat'");
$result = ("SELECT * FROM 'test_prefixCatagory' ORDER by 'Cat'");
while($row = mysql_fetch_array($result))
$sCat = ($row['Cat']);
$sCatID = ($row['CatID']);
{
echo "<table>";
echo "<tr valign='top'><td><b><a href='#".$sCat."'>".$sCat."</a></b><br>";
// column 1 categories
$result2 = ("SELECT * FROM `test_prefixSubCat` WHERE `CatID`=$sCatID");
// sub-cats
while($row2 = mysql_fetch_array($result2))
{
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='#'>".$sSub."</a><br>";
}
echo "<br></td></tr>";
echo "</table>";
}
Do anyone have an idea?
Try this :
<?php
$result = mysql_query("SELECT * FROM `test_prefixCatagory ORDER by `Cat`");
while ($row = mysql_fetch_array($result)) {
$sCat = $row['Cat'];
$sCatID = $row['CatID'];
echo "<table>";
echo "<tr valign='top'><td><b><a href='#" . $sCat . "'>" . $sCat . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM `test_prefixSubCat` WHERE `CatID`='".$sCatID. "'");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = $row2['CatID'];
$sSubID = $row2['SubID'];
echo "<dd><a href='#'>" . $sSub . "</a><br>";
}
echo "<br></td></tr>";
echo "</table>";
}
?>
$result = ("SELECT * FROM `test_prefixCatagory` ORDER by `Cat`");
Not only do you need to add mysql_query but you also need to remove the single quotes from the table name and field name. You can use backticks if you wish but not single quotes around table names.
$result = mysql_query("SELECT * FROM `test_prefixCatagory` ORDER by `Cat`");
// other query:
$result2 = mysql_query("SELECT * FROM `test_prefixSubCat` WHERE `CatID`=$sCatID");
When debugging MySQL problems, use mysql_error() to see a description of the problem.

Categories