Jack
Jack

Reputation: 387

MySQL database connection not working

First time using an external database with android and i'm trying to set up the database connections. I created a basic table in the database just for testing purposes and am trying to connect and insert some data. This is my code:

public class DBInterface {
//TODO: Fix the database connections

    private Connection conn = null;
    private  Statement statement = null;



    public void connectToDatabase(){
        Log.d("myTag", "This is my messagestart");
        try {

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection("jdbc:mysql://mysql.**.***.***.***:3306", "DB_USER", "DB_PASSWORD");
            statement = conn.createStatement();
            statement.executeUpdate("INSERT INTO test (test) VALUES (15)");
            Log.d("myTag", "This is my message");


        } catch (SQLException ex) {
            Log.d("myTag", "SQLException: " + ex.getMessage());
            Log.d("myTag","SQLState: " + ex.getSQLState());
            Log.d("myTag","VendorError: " + ex.getErrorCode());
        }catch(Exception e){e.printStackTrace();}
    }

and I call it in the onCreate of the MainActivity:

         DBInterface db = new DBInterface();
         db.connectToDatabase();
         Log.d("myTag", "This is my message2");

No data is inserted but i also don't get any errors, i put the log messages in to try and see where it was getting to and the only output to the log is:

10-31 16:13:41.481 9918-9918/com.jacksteel.comp4 D/myTag: This is my messagestart

10-31 16:13:41.486 9918-9918/com.jacksteel.comp4 D/myTag: This is my message2

Upvotes: 0

Views: 122

Answers (2)

Kerulija
Kerulija

Reputation: 1

Index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Prijava</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container text-center">
        <h1>VISER twitter</h1><br>
        <input type="text" name="email" id="email" placeholder="Unesite email"> <br><br>
        <input type="text" name="lozinka" id="lozinka" placeholder="Unesite lozinku"> <br><br>
        <button type="submit" name="dugme" id="dugme" class="btn btn-sm ">Uloguj se</button>
        <div id="odgovor"></div>
    </div>
</body>
</html>
<script src="js/index.js"></script>

index.js

$(document).ready(function(){
    $("#dugme").click(function(){
        let unetEmail=$("#email").val();
        let unetaLozinka=$("#lozinka").val();
        $.post("login.php",{email: unetEmail, lozinka: unetaLozinka}, function(response){
            $("#odgovor").html(response)
        })
    })
})

login.php

<?php
session_start();

if(isset($_POST['email'])&&isset($_POST['lozinka'])&&$_POST['email']!=""&&$_POST['lozinka']!=""){
    $email=$_POST['email'];
    $lozinka=$_POST['lozinka'];
    mysqli_report(MYSQLI_REPORT_OFF);
    $db=@mysqli_connect("localhost","root","","pva_k2");
    if(!$db){
        die("greska prilikom prijave na bazu, greska je ".mysqli_connect_errno().": ".mysqli_connect_error());
    }
    $upit="SELECT * from korisnici where email='$email' and lozinka='$lozinka'";
    $rez=mysqli_query($db,$upit);
    if(mysqli_error($db)!=""){
        echo "greska pri izvrsavanju upita ".mysqli_errno($db).": ".mysqli_error($db);
    }else{
        if(mysqli_num_rows($rez)==1){
            while($red=mysqli_fetch_assoc($rez)){
                $_SESSION['ime'] = $red['ime'];
                $_SESSION['prezime'] = $red['prezime'];
                $_SESSION['status']=$red['status'];
                $_SESSION['korisnikid']=$red['id'];
            }
            
            echo '<script>window.location.href = "posts.php";</script>';
            exit();
        }else{
            echo "<div class='alert alert-danger'>Uneti podaci ne odgovaraju ni jednom korisniku</div><br>";
        }
    }

    mysqli_close($db);
}else echo "<div class='alert alert-danger'>Svi podaci moraju biti uneti</div><br>";
?>

Posts.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
    <?php
    session_start();
    echo $_SESSION['ime']." ".$_SESSION['prezime']." ".$_SESSION['status']."<br><a href='odjava.php'>Odjava</a> | <a href='administracija.php'>Administracija</a>";
    if(isset($_POST['email']) && isset($_POST['lozinka']) && !empty($_POST['email']) && !empty($_POST['lozinka'])){
    $email=$_POST['email'];
    $lozinka=$_POST['lozinka'];
    mysqli_report(MYSQLI_REPORT_OFF);
    $db=@mysqli_connect("localhost","root","","pva_k2");
    if(!$db){
        die("greska prilikom prijave na bazu, greska je ".mysqli_connect_errno().": ".mysqli_connect_error());
    }
    $upit="SELECT * from korisnici where email='$email' and lozinka='$lozinka'";
    $rez=mysqli_query($db,$upit);
    while($red=mysqli_fetch_assoc($rez))
    echo "Korisnik: {$red['ime']} {$red['prezime']} {$red['status']}<br> ";
}
    ?>
        <form action="postInsert.php" method="post">
            <input type="text" name="post" id="post" placeholder="Unesite novi post" required> 
            <button class="btn btn-primary btn-sm" name='dugme2' id="dugme2">Snimi post</button>
        </form>
        <h1 class="display-6">Postovi</h1>
        <?php
        $db=@mysqli_connect("localhost","root","","pva_k2");
        $upit="SELECT postovivremek, post, ime, postovi_id, prezime from veza_korisnici_post";
        $rez=mysqli_query($db,$upit);
        while($red=mysqli_fetch_assoc($rez)){
            if($red['ime']==$_SESSION['ime']&&$red['prezime']==$_SESSION['prezime'])
            echo "<div class='siv'>{$red['postovivremek']}<br><b>{$red['post']}</b><br>{$red['ime']} {$red['prezime']}<br><a href='postDelete.php?postovi_id={$red['postovi_id']}' class='btn btn-danger btn-small'>Obrisi</a><br></div>";
        else echo "<div class='siv'>{$red['postovivremek']}<br><b>{$red['post']}</b><br>{$red['ime']} {$red['prezime']}<br></div>";
        }
        ?>
    </div>
    <?php
        mysqli_close($db);
    ?>
</body>
</html>
<script src="js/index.js"></script>

administracija.php

<?php
session_start();

date_default_timezone_set('Europe/Belgrade');

$danasnjiDatum = date("Y-m-d");

$putanja_do_foldera = "C:\\xampp\htdocs\\njuska_sliko\logovi";


if (!file_exists($putanja_do_foldera)) {
    mkdir($putanja_do_foldera, 0777, true);
}


$naziv_datoteke = $danasnjiDatum . ".txt";

$putanja_do_datoteke = $putanja_do_foldera . '\\' . $naziv_datoteke;



    $fajl = fopen($putanja_do_datoteke, "a");


    $tekst = date("H:i:s") . " - Prijava korisnika '" . $email_korisnika . "'" . PHP_EOL;

    fwrite($fajl, $tekst);


    fclose($fajl);

    echo "Podaci su dodati u datoteku: " . $putanja_do_datoteke;

?>

PostInsert.php

<?php
    session_start();
    mysqli_report(MYSQLI_REPORT_OFF);
    $db=@mysqli_connect("localhost","root","","pva_k2");
    if(!$db){
        die("greska prilikom prijave na bazu, greska je ".mysqli_connect_errno().": ".mysqli_connect_error());
    }
    if(isset($_POST['dugme2'])){
        $idKorisnika=$_SESSION['korisnikid'];
        $post=$_POST['post'];
        $upit = "INSERT INTO postovi (idkorisnika, post) VALUES ('$idKorisnika', '$post')";
        mysqli_query($db,$upit);
        echo header("Location: posts.php");
    }
?>

PostDelete.php

<?php
    session_start();
    mysqli_report(MYSQLI_REPORT_OFF);
    $db=@mysqli_connect("localhost","root","","pva_k2");
    if(!$db){
        die("greska prilikom prijave na bazu, greska je ".mysqli_connect_errno().": ".mysqli_connect_error());
    }
    if(isset($_POST['dugme2'])){
        $idKorisnika=$_SESSION['korisnikid'];
        $post=$_POST['post'];
        $upit = "INSERT INTO postovi (idkorisnika, post) VALUES ('$idKorisnika', '$post')";
        mysqli_query($db,$upit);
        echo header("Location: posts.php");
    }
?>

odjava.php

<?php
    session_start();

    session_unset();
    session_destroy();
    
    echo '<a href="index.php">Nazad na pocetnu</a>';
?>

Upvotes: 0

meda
meda

Reputation: 45500

Not a direct answer, but you never want to connect your app directly to your database. Instead you should write some scripts on your server to perform INSERT, SELECT, UPDATE , DELETE.

Your app will then send requests to these scripts to execute the queries.

Upvotes: 1

Related Questions