Dolaps
Dolaps

Reputation: 279

php codes stops running halfway through

I have created a php function that allows users to save their address on the database. My issue is that part of the code doesn't run at all. The code stops running at $result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";

It then starts working when it reaches this line of code $insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress) values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";

I haven't received any syntax errors when running the code either.

Any help would be grateful.

<?php

include 'dbconnect.php';

$connection = mysqli_connect($db_host, $db_username, $db_password, $db_database);
// Check connection
if (mysqli_connect_errno($connection)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Getting data from HTML Form
$Number = $_POST['streetnumber'];
$Street = $_POST['street'];
$Town = $_POST['town'];
$Postcode = $_POST['postcode'];
$Username = $_POST['Username'];

$sql = mysqli_query($connection, "SELECT * FROM Userv2 WHERE Username = '".$Username."'");

if ($sql){
    while($row = mysqli_fetch_array($sql)){

        $id = $row['Id'];

    }
}

$result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";

$sql1 = mysqli_query($connection, $result2);
$count = count($sql1);

if($count >=1){

    echo 'Sorry you can only have 1 default address';
}

$insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress) 
values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";


$result = mysqli_query($connection, $insert_query);

header("Location: http://sots.brookes.ac.uk/~10031187/viewaddress.php");

mysqli_close($connection);
?>

Upvotes: 0

Views: 112

Answers (2)

Taz
Taz

Reputation: 78

$sql1 is a resulset. You cannot count the number of lines like this. Try :

$sql1_count = mysqli_num_rows($sql1) 

Upvotes: 0

klapvee
klapvee

Reputation: 135

maybe it's better to use

SELECT COUNT(Userid) AS countId FROM..
if ($row['countId'] > 1) {

that way the query will always return something, now there is a chance your query can return false..

what is the output of var_dump($sql1); ?

Upvotes: 1

Related Questions