Viewed   95 times

I cannot get my Mysqli queries to both work. If I comment out one function in my html, the other function is properly executed and vice versa.

function all_posts() {
    require_once 'database.inc.php';
    $mysqli = mysqli_connect($host, $username, $password, $database);
    $query = mysqli_query($mysqli, "SELECT variable_name, post_name, post_date, post_display FROM blog_posts ORDER BY id DESC LIMIT 5");

    if (!$query)
        echo mysqli_error();

    while ($results = mysqli_fetch_assoc($query)) {

        $post_name = $results['post_name'];
        $post_date = $results['post_date'];
        $post_display = $results['post_display'];
        $variable_name = $results['variable_name'];

        echo "<a href='posts.php?post={$variable_name}'>";
        echo "<div class='entry'>";
        echo "<div class='entry_header'>";
        echo "<h2>{$post_name}</h2>";
        echo "<h3>{$post_date}</h3>";
        echo "</div>";
        echo "<p>{$post_display}</p>";
        echo "</div>";
        echo "</a>";
    }

    mysqli_free_result();
}

function all_sidebar_posts() {

    require_once 'database.inc.php';
    $mysqli = mysqli_connect($host, $username, $password, $database);
    $query = mysqli_query($mysqli, "SELECT variable_name, post_name FROM blog_posts ORDER BY id DESC LIMIT 5");

    while ($results = mysqli_fetch_assoc($query)) {

        $post_name = $results['post_name'];
        $variable_name = $results['variable_name'];
        echo "<li><a href='posts.php?post=$variable_name'>$post_name</a></li>";
    }

    mysqli_free_result();
}

Here is the html that I am outputting to.

<ul>
    <?php all_sidebar_posts(); ?>
</ul>
</div>
<div class="content_container">
    <?php all_posts(); ?>
</div>

I have tried using mysqli_data_seek(); but haven't had luck. Perhaps I am not using it right? I have browsed many questions and found similar ones but I have tried them all to no avail. I am new to programming so I may be overlooking something basic. Thank you all for the help!

 Answers

3

You are doing it wrong way.
Never mix your data manipulation code with presentation code.

First, get the posts into array:

require_once 'database.inc.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect($host, $username, $password, $database);

$sql = "SELECT variable_name, post_name, post_date, post_display 
        FROM blog_posts ORDER BY id DESC LIMIT 5"
$result = mysqli_query($mysqli, $sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

and then use this $data array to display posts any times you need, simply using foreach()

Monday, September 26, 2022
1

Pseudo code (Won't actually work without some edits to fit your code, but its an idea) - I don't know how your data is stored, or its variable names. Or your table name. Or basically any information that I would need to actually get this to work.

$sql = ("SELECT * FROM ChatLog ORDER BY TimeAdded DESC"); //Order by descending should show the newest ones first.

$index = 1; //set an index to loop through

while($row = mysqli_query($con, $sql) { //use a while loop to go through the table

    if($index <= 50) { //for the first 50 records
        //do nothing
    } else { //for everything after 50 records
        $chatId = $row['chatLogID']; //ID or unique value for the actual message.
        $sql = ("DELETE FROM ChatLog WHERE chatLogID='$chatId'"); //Delete it from the table
        mysqli_query($con, $sql);//Execute query.
    }

}

You can set this up to execute everytime a message is stored, or check it against the current time of the server to remove it daily.

UPDATE: THIS CODE SHOULD BE WORKING WITH YOUR CODE

$sql = ("SELECT * FROM chatbox ORDER BY time DESC"); //Order by descending should show the newest ones first.

$index = 1; //set an index to loop through

while($row = mysqli_query($con, $sql) { //use a while loop to go through the table

    if($index <= 50) { //for the first 50 records
        //do nothing
    } else { //for everything after 50 records
        $chatId = $row['C_ID']; //ID or unique value for the actual message.
        $sql = ("DELETE FROM chatbox WHERE C_ID='$chatId'"); //Delete it from the table
        mysqli_query($con, $sql);//Execute query.
    }

}
Sunday, November 20, 2022
1

To be sure you see all PHP errors, add this code on top of your script:

error_reporting(E_ALL);
ini_set('display_errors', 1);

You must correct your calls to mysqli_real_escape_string. According to the documentation, there must be two parameters, and the first parameter must be a MySQL link. In your case that link would be $mysqli.

Also, replace:

if($row==1){

with:

if($result->num_row==1){

You are misunderstanding what $result->num_rows is: it contains the TOTAL number of rows returned by the query whose result is stored in $result. So, it is useless to check the value of $result->num_rows inside the loop where you retrieve all records returned by the query.

I removed the constant MYSQLI_USE_RESULT from your query() because the documentation for mysqli_query says:
If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result().

New code:

<?php
    $mysqli = new mysqli('localhost', 'root', 'password', 'aiesec');

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %sn", mysqli_connect_error());
        exit();
    }

    // cleanup POST variables
    $myusername = mysqli_real_escape_string($mysqli, stripslashes(trim($_POST['myusername'])));
    $mypassword = mysqli_real_escape_string($mysqli, stripslashes(trim($_POST['mypassword'])));

    // If result matched $myusername and $mypassword, table row must be 1 row
    $sql = "SELECT * FROM members WHERE username='$myusername' and password='$mypassword'"; 
    $result = mysqli->query($sql);
     if($mysqli->errno<>0)
        die("Errormessage: %sn", $mysqli->error);
    echo $result->num_rows;
    if($result->num_rows==1){
        echo "correct username and pass";
        // Register $myusername, $mypassword and redirect to file "login_success.php"
       // session_register("myusername");
        //session_register("mypassword");
        //header("location:login_success.php");
    }
    else {
        echo "Wrong Username or Password";
    }
    mysqli_close();     
?>
Monday, August 1, 2022
 
zac
 
zac
5

Your query looks perfectly fine to me. For the record, this is what the JPA 2.0 specification writes about the MEMBER OF operator:

4.6.13 Collection Member Expressions

The syntax for the use of the comparison operator MEMBER OF in an collection_member_expression is as follows:

   collection_member_expression ::=
            entity_or_value_expression [NOT] MEMBER [OF] collection_valued_path_expression
   entity_or_value_expression ::=
            single_valued_object_path_expression |
            state_field_path_expression |
            simple_entity_or_value_expression
   simple_entity_or_value_expression ::=
            identification_variable |
            input_parameter |
            literal

This expression tests whether the designated value is a member of the collection specified by the collection-valued path expression.

Expressions that evaluate to embeddable types are not supported in collection member expressions. Support for use of embeddables in collection member expressions may be added in a future release of this specification.

If the collection valued path expression designates an empty collection, the value of the MEMBER OF expression is FALSE and the value of the NOT MEMBER OF expression is TRUE. Otherwise, if the value of the collection_valued_path_expression or entity_or_value_expression in the collection member expression is NULL or unknown, the value of the collection member expression is unknown.

Example:

SELECT p
FROM Person p
WHERE 'Joe' MEMBER OF p.nicknames

So, because I can't see anything wrong in your query, I've tested your code with EclipseLink1 and the following snippet just works:

Query query = em.createQuery("SELECT u FROM User u WHERE 'admin' MEMBER OF u.roles");
List list = query.getResultList();

But fails indeed with Hibernate EntityManager 3.5.1-Final. This sounds like a bug, feel free to raise a Jira issue.

1 Just in case, I used the following Maven profile (for the JPA provider):

  <profile>
    <id>eclipselink</id>
    <repositories>
      <repository>
        <id>eclipselink</id>
        <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo/</url>
      </repository>
    </repositories>
    <dependencies>
      <!-- See http://wiki.eclipse.org/EclipseLink/Maven -->
      <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.0.0</version>
      </dependency>
      <!-- optional - only needed if you are using JPA outside of a Java EE container-->
      <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>javax.persistence</artifactId>
        <version>2.0.0</version>
        <scope>provided</scope>
      </dependency>              
    </dependencies>
  </profile>

And this is my persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence
    xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">

  <persistence-unit name="TestPu" transaction-type="RESOURCE_LOCAL">    
    <class>com..q2688144.User</class>    
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:testdb;create=true"/>    
      <property name="eclipselink.target-database" value="DERBY"/>
      <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
    </properties>
  </persistence-unit>
</persistence>

Update: reported in HHH-5209

Wednesday, August 3, 2022
 
111
 
111
3
while ($row = mysqli_fetch_array($stmt)) {
    echo "<tr>";
    echo "<td>" . $row["aid"] . "</td>";
    echo "<td>" . $row["aname"] . "</td>";
    echo "</tr>";
}
Saturday, November 5, 2022
 
sunn0
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :