This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
I saved a value as a cookie and then checked if there exists in the perfiles_vinculados table to get all the data that has the same id in the perfil table.
Then I create an array of the $vinculado result and show it in a HTML table as a row.
The problem is that the console returns:
Catchable fatal error:
Object of class mysqli_result could not be converted to string in
C:\xampp\htdocs\miramonteapp\api\modal.php
The cookie:
document.cookie = "vinculaciones=" + $("#mod_id_perfil").val();
PHP:
//querys
<?php
include 'api/conexion.php';
$ides = $_COOKIE['vinculaciones'];
$juridicos = "SELECT perfil_juridica FROM perfiles_vinculados where perfil_fisica = '$ides'";
$con = mysqli_query($conexion, $juridicos);
$vinculado = mysqli_query($conexion, "SELECT * FROM perfil where id = '$con'");
?>
//table
<?php
while($reg = mysqli_fetch_array($vinculado)) {
$id = $reg['id'];
?>
<tr id="<?php echo " tr_ ".$reg['id']; ?>">
<td class="" data-id="<?php echo $reg['usuario'] ?>">
<?php echo $reg['nombre']; ?>
</td>
<td class="" data-id="<?php echo $reg['usuario'] ?>">
<?php echo $reg['cuit']; ?>
</td>
<td class="td-actions text-right">
<button type="button" rel="tooltip" class="btn btn-danger">
<i class="material-icons">close</i>
</button>
</td>
<?php } ?>
You have to learn about join sql statement.
As for you current approach, first you need to fetch perfil_juridica value from a result of $juridicos execution and then pass this value to your second query:
// first query
$juridicos = "SELECT perfil_juridica FROM perfiles_vinculados where perfil_fisica = '$ides'";
$result = mysqli_query($conexion, $juridicos);
$row = mysqli_fetch_array($result);
$perfil_juridica = $row['perfil_juridica'];
// second query
$vinculado = mysqli_query($conexion, "SELECT * FROM perfil where id = '$perfil_juridica'");
What you should do next is move to prepared statements instead of putting unsafe values into query texts. This question will help you.
Related
This question already has answers here:
Echo current number of row
(3 answers)
Closed 1 year ago.
I have a query that I make using PHP and it returns me all the rows that satisfied the condition that was given, now, I'm wondering if there's a way to count each number of row a result of a query has and pass that number to an id of an element on HTML?
<?php
$res2 = mysqli_query($con,"SELECT NAME, PRICE FROM product WHERE AVAILABLE = 1 AND ID_CATEGORY = 17");
?>
<body>
<?php
while($row = mysqli_fetch_row($res2)) {
print_r($row);
?>
<div class="item">
<img class="trj_img_cls" src="RSC/COMING_SOON.jpg" alt="" id="imgDG<?php ?>">
<div class="texto_trj">
<div class="nombre_producto">
<h2 id="ttlDG<?php ?>">tÃtulo</h2>
</div>
<div class="precio_producto">
<i class="icon-dollar"></i>
<label id="prDG<?php ?>">0.00</label>
</div>
<div class="caracteristicas">
<ul id="caractDG<?php ?>"></ul>
</div>
</div>
</div>
<?php
}
?>
</body>
I put <?php ?> because there I want to add the variable (number of the row) so it complements the actual id and then i'm able to look for that id with javascript. Another thing is that I use the print_r() just to see if the elements were appearing.
This can be done by setting an $increment variable to 1 at the start of the while loop, and incrementing it at the end of the loop.
<?php
$increment = 1;
while($row = mysqli_fetch_row($res2)) {
And then using it like this:
id="imgDG<?php echo $increment; ?>">
And then incrementing it at the end:
<?php
$increment++;
}
?>
I am trying to make a forum-like website from scratch and this is the first big problem that I encountered so far, I am trying to make an individual link with ?info[id] for each ticket/topic but I simply can't, no matter what id I put in the url, I see all of them instead of the specific one, you have all the code in the video.
Video Link
My Details.php Code
<?php
require('Includes/Header.php');
$query = "SELECT * FROM forum";
$result = mysqli_query($conn ,$query);
?>
<?php while($row = mysqli_fetch_array($result)) {?>
<div class="FormAfter">
<label>ID</label><br><br>
<span><?php echo htmlspecialchars($row['id']); ?></span><br><br>
<label>Titlu</label><br><br>
<span name="Titlu"><?php echo htmlspecialchars($row['titlu']);?></span><br><br>
<label>Categorie</label><br><br>
<span><?php echo htmlspecialchars($row['categorie']); ?></span><br><br>
<label>Descriere</label><br><br>
<span name="Descriere" cols="30" rows="10" readonly><?php echo htmlspecialchars($row['descriere']);?></span>
</div>
<?php
}
mysqli_close($conn);
?>
This is my Topics.php code
<?php
require('Includes/Header.php');
$query = "SELECT * FROM forum";
$result = mysqli_query($conn ,$query);
?>
<div class="TopicListBig">
<span id="IdTitlu">ID <strong>|</strong> Titlu <strong>|</strong> Categorie</span> <br> <br> <br>
</div>
<?php
while($row = mysqli_fetch_array($result)){ ?>
<div class="RandomSpan">
<span class="TopicList"><?php echo htmlspecialchars($row['id']); ?></span>
<span class="TopicList"><?php echo htmlspecialchars($row['titlu']); ?></span>
<span class="TopicList"><?php echo htmlspecialchars($row['categorie']); ?></span>
<span class="TopicList">Info</span><br><br>
</div>
<?php
}
mysqli_close($conn);
?>
Your SQL query is explicitly fetching all records: "SELECT * FROM forum" It's the exact same query in Details as it is in Topics and nowhere in the code for Details do you make use of the id parameter in the URL's query string.
What you're looking for in that SQL query is the WHERE keyword. For example:
SELECT * FROM forum WHERE id=?
Within your WHERE clause you identify the specific filter to find the exact record(s) you want. Then you bind your value to that parameter before executing the query. While that link shows the (generally preferred) object-oriented style, you can also use the procedural style you currently use. For example:
$query = mysqli_prepare($conn, 'SELECT * FROM forum WHERE id=?');
mysqli_stmt_bind_param($query, 's', $_GET['id']);
mysqli_stmt_execute($query);
$result = mysqli_stmt_get_result($query);
while ($row = mysqli_fetch_array($result)) {
// your output
}
so, I'll try to explain it as good as I can with my knowledge in english.
I am trying to count data from my database, basically - how many fields I have with the same ID. here's image from database.
image from database
for example, in posts i have review system and it works, i have this PHP code to count how many same fields i have with review and id.
Here's the code:
<?php
$revposid = $res['content_id'];
$pos="SELECT review FROM comments WHERE review='positive' and postid=$revposid";
$neg="SELECT review FROM comments WHERE review='negative' and postid=$revposid";
$neu="SELECT review FROM comments WHERE review='neutral' and postid=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neg)){$rowcountneg=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neu)){$rowcountneu=mysqli_num_rows($result);}
?>
<div class="reviews" id="reviews">
<span class="good"><b class="fa fa-thumbs-up"></b><?php echo $rowcountpos ?></span>
<span class="neutral"><b class="icon-thumbs-up"></b><?php echo $rowcountneu ?></span>
<span class="bad"><b class="fa fa-thumbs-down"></b><?php echo $rowcountneg ?></span>
</div>
and when I try to use the same code
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
in my other script I have like system, it should show all my likes and under likes total likes of the post but when I use it it shows unlimited amount of data, i have no idea why. Here's the full code, I would appreciate some help or explanation.
<?php $ususername = $_GET['user_username'];$sql = "SELECT * FROM user_details WHERE user_username='$ususername'";$usresult = mysqli_query($_db,$sql);?>
<?php if( ! mysqli_num_rows($usresult) ) {
echo " Ooops? <br> <br>User <b>".$_GET["user_username"]."</b> doesn't exist.";
} else {
while($usrow = mysqli_fetch_array($usresult,MYSQLI_BOTH)) {?>
<?php
$current_user = $usrow['user_id'];
if ($_db->connect_error) {
die("Connection failed: " . $_db->connect_error);
}
$sql = "SELECT * FROM user_content_like WHERE user_id=$current_user ORDER BY date_added DESC;";
$result = $_db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$content_id = $row['content_id'];
$sql1 = "SELECT * FROM content WHERE content_id=$content_id";
$result1 = $_db->query($sql1);
if ($_SESSION['user_id'] == $usrow['user_id']) {$output = '
<button type="button" class="unlike_button" onclick="unlike(this);" name="like_button" data-content_id="'.$row["content_id"].'" ><i class="fa fa-minus"></i></button>
';} else {
$output = '';
}
while($cont = $result1->fetch_assoc()) {
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
echo '
<div class="community-feed-thread">
<div class="community-icon-thread"></div>
<div class="community-comments-thread">'.$output.'</div>
<a href="'.$cont["content_id"].'" class="community-title-thread"><h3>'.$cont["title"].'</h3>
<span class="likes-desc"> Total likes: '.$rowcountpos.'</span>
</a>
</div>
';
}
}}
else {
echo " hmmmmmmmmmmmm.<Br><br>". $usrow["user_username"]." doesn't like anything. ";
}
$_db->close();
?>
<?php }}?>
this is how i want it to look
This is how it looks
Your re-using the same variable for different result sets in the code...
$result = $_db->query($sql);
and
if ($result=mysqli_query($_db,$pos))
You will need to ensure you only use the variable name once or it may have side effects in other loops.
I made code which loads online players from game server(through MySQL table). Now, I'm newbie in PHP and I don't Know how to sort them(users) in table by ID. I googled and I found answer which will sort arrays by value(1, 2, 3, 4 etc..). Only problem is because users, with ID, have a name. How to connect user's name with ID, so they stay together after sort?
Here's a code
while($_hsync_podatci = $_hsync_rezultat->fetch_assoc())
{
?>
<tr class="_hsync_online_stil_<?php echo $_hsync_dio; ?>" id="_hsync_na_mrezi_<?php echo $_hsync_podatci['ServerID']; ?>">
<td><?php echo $_hsync_podatci['ServerID']; ?></td>
<td><?php echo $_hsync_podatci['Ime']; ?></td>
<td>
<button type="button" id="_hsync_izbaci_<?php echo $_hsync_podatci['ServerID']; ?>" class="btn btn-danger" onclick="_hsync_izbaci(<?php echo $_hsync_podatci['ServerID']; ?>)" style="float: right;">
<span class="glyphicon glyphicon-log-out"></span>Izbaci
</button>
</td>
</tr>
<?php
$_hsync_dio = !$_hsync_dio;
}
Above while is table's header. Var $_hsync_dio is for background color. One row is white, second is grey, and so on.
When doing a MySQL query you can sort the array automatically when fetching the data for example:
$players = mysqli_query($conn, "SELECT * FROM playerTable ORDER BY id ASC");
while($row = mysqli_fetch_assoc($message_sender_info)){
$message[] = $row;
}
Use DESC instead of ASC for e reverse sorting.
I have two queries from two tables one is properties and second is images of properties.
The PropertyID field is available in both tables which have relationship of PK--->FK.
NOW my question is here how can I use the value of propertyID which I have received in
the first query and use it in the second one for retrieving the images of each property.
I 've wrote some code, but I receive this error message:
Notice: Trying to get property of non-object in C:\xampp\htdocs\Scale-Property\spd\index.php on line .......
Here is my code:
<?php
require_once('../Admin Panel/db.php');
if(isset($_POST['Province']) && isset($_POST['District']) && isset($_POST['radio']))
{
$provincename=$_POST['Province'];
$districtname=$_POST['District'];
$propertystatus=$_POST['radio'];
$query = "SELECT
properties.PropertyID,
properties.PropertyName,
some other fields......,
Provinces.ProvinceName,
districts.DistrictName,
pds.PDName,
propertyimages.PropertyID
FROM properties, provinces, districts, pds, propertyimages
WHERE Provinces.ProvinceID=Properties.ProvinceID
AND districts.DistrictID=Properties.DistrictID
AND pds.PDID=properties.PDID
AND ProvinceName='".$provincename."'
AND DistrictName='".$districtname."'
AND PropertyDealType='".$propertystatus."'
ORDER BY properties.PropertyID";
$queryrun= $connection->query($query); // first query run in here
while ($row= $queryrun->fetch_assoc()) // in here trying to store the propretyID
{
if( $connection->error ) exit( $connection->error );
$count= $queryrun->num_rows;
echo 'You Have Got <b>'. $count .' </b>out of 326 Records';
while($row = $queryrun->fetch_assoc())
{
$imagequery ="SELECT PropertyID, ImagePath, ImageName, FROM properties WHERE PropertyID = '".$row['PropertyID']."'";
// Now i want to use the stored value of propertyID in here for retrieving the
Images of related property
}
$imagequery_run= $connection->query($imagequery);
if($imagequery_run->num_rows > 0)
{
while ($imagerow = $imagequery_run ->fetch_assoc())
{
?>
<div class="propertywrapperviewmore">
<div class="propertysingleimageviewmore">
<a href="property.php?PropertyID=<?php
echo htmlentities($imagerow['PropertyID']) ?>&PropertyID=<?php echo htmlentities($propertyrow['PropertyID']) ?>">
<img src="<?php echo htmlentities($imagerow['ImagePath']) ?>" width="227" height="147" alt="<?php echo htmlentities($imagerow['ImageName']) ?>" ></a>
</div>
<div class="propertyIDviewmorelablevalue">
<div class="propertyIDL">Property ID:</div>
<div class="propertyIDV"><?php echo $row['PropertyID']?></div>
</div>
<div class="propertyIDviewmorelablevalue">
<div class="propertyIDL">Property Name:</div>
<div class="propertyIDV"><?php echo $row['PropertyName']?></div>
</div>
</div>
<?php
}
}
}
}
?>
Like Burhan Khalid suggested, you need to join the tables like this:
select [listOfFields]
from properties p
join propertyimages pi
on p.propertyid = pi.propertyid
where [youWhereClauses]
Where the on part links the PK and FK of the tables.
Check the mysql syntax here: http://dev.mysql.com/doc/refman/5.0/en/join.html