php codes stops running halfway through - php

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);
?>

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); ?

$sql1 is a resulset. You cannot count the number of lines like this.
Try :
$sql1_count = mysqli_num_rows($sql1)

Related

adding user info and log in info in different page

so I want to make a sign up where at the first page, is the user info where the name, last name etc will be input by the user, then it will be recorded into the database and redirect to the account info page where the user input the username and password and be recorded in another database so I have to tables the student, where all the info is stored, and user, where account info is stored so the userID of the user will be the foreign key of in the student but I cant put the id number of the user to the table of the student where the first input is stored in the first page, so if I use the mysqli_insert_id it can insert the id of the last inserted user into the student table but into the next row not the row where the last input of information in the first page is located
code in the first page shs/functions/add.stud.php
<?php
session_start();
include 'database.php';
if (isset($_POST['add'])) {
echo "welcome";
}
$message = "Provide all information needed please";
$lname = $_POST['Lname'];
$fname = $_POST['Fname'];
$mname = $_POST['Mname'];
$email = $_POST['email'];
$grade = $_POST['grade'];
$strand = $_POST['strand'];
$section = $_POST['section'];
$status = $_POST['status'];
if (empty($lname) || empty($mname)) {
header("Location:../pages/user.add.php?empty=put something, will ya?");
exit();
}
else {
$sql = "INSERT INTO student (lname, fname, mname, gmail, grade, track, section, status)
VALUES ('$lname', '$fname', '$mname','$email', '$grade', '$strand', '$section', '$status')";
$result = mysqli_query($conn, $sql);
}
then in the account information (username, password)
<?php
if (isset($_POST['users'])){
include_once 'database.php';
$uid = $_POST['uid'];
$pass = $_POST['pass'];
//pag check or pag handle sa mga errors sa pag log in
if (empty($uid) || empty($pass))
{
header("location:../pages/user.add.php?signup=empty fields");
exit();
} else {
$sql = "SELECT * FROM 'user' WHERE username ='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 0) {
header("Location:.../user.add.php?the inputs are already taken");
exit();
}
else {
$hashedpass = password_hash($pass, PASSWORD_DEFAULT);
//insert the new user to the user database
$sql = "INSERT INTO user (userID, username, password)
VALUES (NULL, '$uid', '$hashedpass');";
$result = mysqli_query($conn, $sql);
//pag connect sa student database
//katung sa database sa image
$sql = "SELECT * FROM user WHERE username ='$uid'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)){
$userid = $row['userID'];
$sql = "INSERT INTO profileimg (userID, status)
VALUES ('$userid', 1)";
if($result=mysqli_query($conn, $sql))
{
$last_id = mysqli_insert_id($conn);
$sql = "INSERT INTO student (userID) VALUES ('$last_id')";
$result = mysqli_query($conn, $sql);
}
else {
header("Location:.../user.add.php");
exit();
}
//pag add sa id sa user paingun sa student
header("Location:../pages/user.add.php");
}
}
after putting the inputs in the first page it will redirect to another page where the user must input the account info..that's the desired function
The best way is to store the User Info in the student table then use the mysqli_insert_id function to grab the studentId. Then save the Account Info in the user table and grab the userId. Thereafter update the student table with userId where studentId is the same as the one you grabbed earlier.
$sql = "INSERT INTO student (lname, fname, mname, gmail, grade, track, section, status)
VALUES ('$lname', '$fname', '$mname','$email', '$grade', '$strand', '$section', '$status')";
$result = mysqli_query($conn, $sql);
$_SESSION['studentId'] = mysqli_insert_id($conn); //add this line to store the studentId into the session.
$sql = "INSERT INTO student (userID) VALUES ('$last_id')"; // change this line to the one below.
$sql = "UPDATE student SET userID = '$last_id' WHERE studentID = $_SESSION['studentId']";

Can't insert data into mysql with php

ok so I can connect and view the database with my php code, however I can not insert data into it.here is the query I tested with phpmyadmin which was able insert new data into my table
INSERT INTO `members` ( `id` , `username` , `email` )
VALUES ( 123456789, 'russi', 'baka#dog.com' )
then I tried to put it into my actual php file
<?php
$servername = "localhost";
$username = "root";
$password = "blablabla";
$dbname = "test_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - username: " . $row["username"]. " -email:" . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
so select function works but insert does not.
You are overriding your $sql variable w/o executing it. Besides that you should not use single quotes for columns, but backticks (see When to use single quotes, double quotes, and backticks in MySQL)
Change
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
to
$sql = "INSERT INTO `members` (`id`, `username`, `email`)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$result = $conn->query($sql);
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
Change your insert to:
$sql = "INSERT INTO members (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
And call your query:
$sql = "INSERT INTO members (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
//Here, you never execute your query
$result = $conn->query($sql);
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
Of course it did not work !
You never execute your INSERT...
<?php
...
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$conn->exec($sql);
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
...
:)
remove the single quotes around your column and table names:
$sql = "INSERT INTO members (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
single quotes are only used for char fields.
Also you never execute the insert Statement because you overwrite it.
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT id, username, email FROM members";
//missing the grave accent
$sql = "INSERT INTO `members` (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT `id`, `username`, `email` FROM `members`";
/* This is the corrrected code */

Check if name already exist

I have this code.
This code can check if form number is already existing in the database.
Now i want to check if the firstname and lastname is already existing.what and where should i
$FNresult = mysql_query("SELECT COUNT(*) FROM profile WHERE FormNo = '$FrmN' ");
if (!$FNresult) {
die(mysql_error());
}
if (mysql_result($FNresult, 0, 0) > 0) {
echo "<br>Form number already exist!";
}
else {
$sql = "INSERT INTO profile
(FormNo, FirstName, LastName, Address, Email, MobileNo,
LandlineNo, Amount, Term, Manner)
VALUES ('$FrmN', '$FN', '$LN', '$ADD', '$E', '$MOBILE',
'$LAND', '$AMNT', '$TRM', '$MNNR')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<br>1 record added!";
}
mysql_close($con);
$sql = mysqli_query("SELECT firstname,lastname FROM profile WHERE firstname = '$firstname' and lastname = '$lastname'");
$rownum = mysqli_num_rows($sql);
if( $rownum > 0 )
die('Your name already exists in database');
Note = I wrote mysqli_* but you are using mysql_*
You can change it depending on how you want it to be.
You should change your mysql_* to mysqli_* as the first one has been deprecated and will be deleted in the future
Something similar to the code above must do the trick.
Good Luck

Passing space in parameters to php file

I have a table name "User" writen in MySQL with the fields: UserID, UserName, Password, eMail, DisplayName, Score, timeStamp. The field UserID is int AUTO_INCREMENT and time stamp is dateTime. I'm trying to insert values into the table using php file. This is my php file:
mysql_connect("mysql.1freehosting.com","u948577195_uname","p7CraCuRAw");
mysql_select_db("u948577195_dbnam");
$uName = $_GET['uname'];
$pass = $_GET['password'];
$mail = $_GET['email'];
$disName = $_GET['disnam'];
$date = $_GET['dt'];
$sql=mysql_query("INSERT INTO User
VALUES ('$uName', '$pass', '$mail', '$disName', 0, '$date')");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
I activate the file using this connection string:
http://pickupfriend.fulba.com/android_project/query3.php?uname=Test&password=p1&email=ml&disnam=Test&dt=21:12:30 2014-07-07
I have a space between the seconds and the year in the date, is it OK? After I run the connection string I receive this error:
Parse error: syntax error, unexpected T_STRING in /home/u948577195/public_html/android_project/query3.php on line 13
What am I doing wrong? How to correct my connection string?
Thank you in advance!
Your link shows that you are getting the parameters wrong in the $_GET part.
Hence you must delete this line as it's not php
INSERT INTO [USER]
VALUES ('$uName', '$pass', '$mail', '$disName', 0, '$date')
Change your code as as below.
mysql_connect("mysql.1freehosting.com","u948577195_uname","p7CraCuRAw");
mysql_select_db("u948577195_dbnam");
$uName = $_GET['uname'];
$pass = $_GET['pass'];
$mail = $_GET['mail'];
$disName = $_GET['disName'];
$date = $_GET['date'];
$sql = mysql_query("INSERT INTO User VALUES ('$uName', '$pass', '$mail', '$disName', 0, '$date')");
if (!$sql) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
mysql_close();
And your are not fetching anything within your query, if your aim is to see all add this before mysql_close()
$query = mysql_query('SELECT * FROM User');
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
$output = array();
while ($row = mysql_fetch_assoc($query) !== false) {
$output[] = $row;
}
echo json_encode($output);
And what do you expect to happen?
INSERT INTO [USER]
VALUES ('$uName', '$pass', '$mail', '$disName', 0, '$date')
That is NOT php! You forgot to use it in a query or something.

Update values which match the same ip php/sql

<?
$nick = $_POST['nick'];
$link = $_POST['link'];
$regiment = $_POST['regiment'];
$message = $_POST['message'];
$date = date('Y-m-d H:i:s');
$ip = $_SERVER['REMOTE_ADDR'];
$servername="localhost";
$username="pp";
$conn= mysql_connect($servername,$username, mygas13)or die(mysql_error());
mysql_select_db("pp",$conn);
$ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$sql = "SELECT TIMEDIFF(NOW(), `LastPost`) AS 'TimeSinceLast'
FROM `userTable`
WHERE `ip` = '{$ip}'
AND `LastPost` > DATE_SUB(NOW(), INTERVAL 1 DAY)";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$timeSinceLast = date("G\h i\m s\s", strtotime($row['TimeSinceLast']));
$sql="insert into userTable (nick,link,message,regiment,ip,date,submitted) VALUES ('$nick', '$link', '$message', '$regiment', '$ip', '$date', 'Yes') ";
$result=mysql_query($sql,$conn) or die(mysql_error());
}
else {
$servername="localhost";
$username="pp";
$conn= mysql_connect($servername,$username, mygas13)or die(mysql_error());
mysql_select_db("pp",$conn);
$sql="insert into userTable (nick,link,message,regiment,ip,date,submitted) VALUES ('$nick', '$link', '$message', '$regiment', '$ip', '$date', 'No')";
$result=mysql_query($sql,$conn) or die(mysql_error());
mysql_close($connection);
}
header("Location: thanks.html");
?>
This is my input.php. It submits the data but it also checks if multiple submissions come from one ip in 1day period. What i can't do is to update the value submitted for the rest of his/her submissions with yes. I have tried DUPLICATE KEY UPDATE but it did not work

Categories