Showing posts with label Mysqli Query. Show all posts
Showing posts with label Mysqli Query. Show all posts

Monday, 3 September 2018

The php code works correctly and does not request the database

I'm using php and a database to add books to a database.

HTML
<form method="POST" action="addbook.php">
<p>Enter Book title :<input type="text" name="bookname"></p>
<p>Enter Book Author :<input type="text" name="bookauthor"></p>
<p><input type="submit" value="addbook"></p>
</form>

PHP
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbcon = mysqli_connect('localhost','root','password','bookstore') or die('asd');

$dbquery = "INSERT INTO books (title,author) VALUES ($bname,$bauthor)";

mysqli_query($dbcon,$dbquery) or die('not queryed');

echo "Your book has been added to your online library";

I'm getting the reply ' not queryed'

try putting single quotes around the values
ie
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";

Tuesday, 28 August 2018

Mysqli queries does not return results in function

I have several php functions which serve different purposes. Each of them is executing a specified mysqli query yet only the first query returns results.

Here is my code
function setAsNonWorkingProxy(){

    GLOBAL $mysqli, $proxy;

    $port = explode(":",$proxy)[1];
    $proxy = explode(":",$proxy)[0];

    if ($sql2 = $mysqli->prepare("UPDATE proxies SET failed=failed+1 WHERE ip=? AND port=?")) {

        $sql2->bind_param("si",$proxy, $port);

        $sql2->execute();

        $sql2->close();

    }
}

function markProxyAsUsed(){

    GLOBAL $mysqli, $proxy;

    $port = explode(":",$proxy)[1];
    $proxy = explode(":",$proxy)[0];

    if ($sql3 = $mysqli->prepare("UPDATE proxies SET tried=tried+1 WHERE ip=? AND port=?")) {

        $sql3->bind_param("si",$proxy, $port);

        $sql3->execute();

        $sql3->close();
    }
}

setAsNonWorkingProxy();
markProxyAsUsed();

When I do this, only the first function that is called, executes the query inside. The second function is called and the query executed without any errors yet nothing happens. I am using UDPDATE queries inside both functions.
If I change the order of the functions:
markProxyAsUsed();
setAsNonWorkingProxy();

Again, only the first one works. Why is this happening?

The problem is that you are bringing the global scope variable in your function. Then using explode on the $proxy and the result is stored back into $proxy(remember thats the same global var) what happens is that the second function called is now working with the modified $proxy variable. It doesn't even matter if you call the same function two times, it will fail the second time.
function markProxyAsUsed(){

    GLOBAL $mysqli, $proxy; //You are bringing global scope vars in here

    // If $proxy is something like '222.222.222.222:8080' on your first call
    // On the second call will be only '222.222.222.222' and your logic will be broken
    $port = explode(":",$proxy)[1];
    $proxy = explode(":",$proxy)[0]; //Here is where you are messing it
    //Quickfix
    $ip = explode(":", $proxy)[0]; // then use $ip in your query

    //Proper fix would be to declare the function as so function markProxyAsUsed($proxy)
    //and pass it when you call the function.

MySQLi Query does not return results correctly

I'm trying to switch my website over to MySQLi and I'm following the W3schools MySQLi guide to do so. I've hit a roadblock, though. I have a function to check if a specified user is an admin on the site. I've put echo in various spots to find where the issue is, and I've figured out that it most likely doesn't see the user. $username is set to the variable $user. Here's the whole code block (part of connect.php:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if(!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

session_start();
if(!isset($_SESSION["user_login"])) {
    $user = "";
} else {
    $user = $_SESSION["user_login"];
}

//functions
function isAdmin($username) {
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "lark";
    $conn = mysqli_connect($servername, $username, $password, $dbname);

    $sql_get_is_admin = "SELECT * FROM users WHERE username='$username' LIMIT 1";
    $get_is_admin = mysqli_query($conn, $sql_get_is_admin);

    if(mysqli_num_rows($get_is_admin) > 0) {
        echo "num_rows";
        while ($row = mysqli_fetch_assoc($get_is_admin)) {
            $is_admin_bool = $row['admin'];
            echo "while";
            if($is_admin_bool == 0){
                return false;
            } elseif ($is_admin_bool == 1) {
                return true;
            }
        }

    } else {
        echo "not found.";
    }
}
?>

Here's the code I used to test the $user variable:
<?php
include("connect.php");
?>
<div class="main">
<h1>Welcome back, <?php echo $user; ?></h1>
foo
<?php
/*if(isAdmin($user) == true) {
    echo   "<div style='display: table-cell;' class='rightcell'>
                <h3 style='color: #000;'>Admin Tools</h3>
                <a href='userlist.php' target='_blank'>Userlist</a>
            </div>";
} else {
} */

echo isAdmin($user);
?>
</div>

I also had to reconnect to the database or else I'd get this error on the site:
Notice: Undefined variable: conn in C:\xampp\htdocs\lark\connect.php on line 33

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\lark\connect.php on line 33

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\lark\connect.php on line 35 not found.

If I fix it so there's no error, it just says "not found."

You don't have $conn in your function, it is commented out.
function isAdmin($username) {
    /*$servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "lark";
    $conn = mysqli_connect($servername, $username, $password, $dbname);*/

The Mysqli query does not return any information?

Im attempting to find the next date. For what ever reason, the below code is not returning any information. I have 1 entry formatted as such : 2017-03-18 12:37:00.... what am I doing wrong?

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'pass');
define('DB_DATABASE', 'db');
$link = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$query = "SELECT * FROM group WHERE date_time >= NOW() order by date_time LIMIT 1";
$next = mysqli_query($link, $query);
echo $next;
?>


You need to call a fetch function to get the data from the query. You should also check if it found anything; the fetch function will return null instead of an array if no rows were matched by the query.
$query = "SELECT * FROM `group` WHERE date_time >= NOW() ORDER BY date_time LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);
if ($row) {
    $date_time = $row['date_time'];
    echo "Next date is " . $date_time;
} else {
    echo "No time after now in the table.";
}