I want to make toefl test. I make table score_structure in database containing 4 columns (email, right, false, score). If the user has done on previous test and will perform a test again, then the user data will be updated according to the user's email pitch.
I have tried but failed, the data will not update. Please help me.
This is structure.php
<?php
$email = $_SESSION['email'];
$cek = mysql_num_rows(mysql_query("SELECT email FROM score_structure WHERE email='$email'"));
if($cek > 0 ) {
$simpan = "UPDATE score_structure SET right='$right', false='$false', score='$score' WHERE email='$email'";
if(mysql_query($simpan)) {
header("location:test_listening.php");
} else {
echo mysql_error();
} else {
$simpan = "INSERT INTO score_structure VALUES ('$email', '$right', '$false', '$score')";
if(mysql_query($simpan)) {
header("location:test_listening.php");
} else {
echo mysql_error();
}
}
?>
Update your update query & let us know the feedback:
$simpan = "UPDATE score_structure SET `right`='$right', `false`='$false', `score`='$score' WHERE email='$email'";
Also currently mysql_() are depreciated so use mysqli_()
Related
I am Android developer and trying to make one API for register user using PHP and Mysqli. I have made API like below
<?php
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
$response='success';
}else{
$sql = "INSERT INTO tbl_user(email)VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response='success';
}else {
$response='error';
}
}
echo json_encode($response);
?>
basically I am passing email as parameter like example.com/login?=abc#gmail.com
and I want check that email is already in database table or not. if email exist in database I want return user_id in response and if email is not in database than I want add that email in database and want return user_id. I have made API is working fine as I require but I do not know how to return user_id located with that email. Let me know if someone can give me idea to solve my puzzle. Thanks
The below code will create an array with message and user_id.
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
// assign message to response array
$response['message']='success';
// Get the results data
while($row = mysqli_fetch_assoc($query)) {
// assign user_id to response array
$response['user_id'] = $row['user_id'];
}
}else{
$sql = "INSERT INTO tbl_user(email) VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response['message']='success';
// assign last inserted id to response array
$response['user_id'] = mysqli_insert_id($conn);
}else {
$response['message']='error';
}
}
echo json_encode($response);
Prepared statements help you secure your SQL statements from SQL Injection attacks.
First of all, you should use PreparedStatement to avoid sql injection.
Then, second you can use PDO::lastInsertId()
I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?
$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
Using data from an activation email. $email & $key.
$result1 mysql_query -
The result is that only the email, role, credits are inserted into table users. Data items username, password are not inserted.
$result2 mysql_query -
The data is not deleted from table tempusers
If I echo the data from the while loop the correct data is returned.
Got to be something simple but I just cannot see it. Thanks.
CODE:
include 'core/init.php'; /* database connection*/
if (isset($_GET['email']) && preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_GET['email'])){
$email = mysql_real_escape_string($_GET['email']);
}
if(isset($_GET['key']) && (strlen($_GET['key']) == 32)) {
$key = mysql_real_escape_string($_get['key']);
}
if(isset($email) && isset($key)) {
$result = mysql_query("SELECT * FROM `tempusers` WHERE `email` = '$email' AND `activation` = '$key' ") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user_id = mysql_real_escape_string($row['user_id']);
$username = mysql_real_escape_string($row['username']);
$email = mysql_real_escape_string($row['email']);
$password = mysql_real_escape_string($row['password']);
}
$result1 = mysql_query("INSERT INTO `users` (`username`, `email`, `password`, `role`, `credits`) VALUES ('$username', '$email', '$password', 'user', 0)") or die(mysql_error());
$result2 = mysql_query("DELETE FROM `tempusers` WHERE `user_id` = '$user_id'") or die(mysql_error());
if(!$result1) {
echo "Oops your account could not be activated. Please contact the system administrator!";
} else {
header('Location: prompt.php?x=0');
}
} else {
echo "Error. Please contact the system administrator!";
}
?>
Are you sure the query goes execute? And are you also sure the query have at least 1 result? The $email is already set but to set the username and passwors your query needs to have at least 1 result.
I also noticed $_get['key'] but i am not sure if its neccecary to change it to $_GET['key'].
This $_get in => mysql_real_escape_string($_get['key']) is in lowercase letters.
$_GET is a superglobal and it must be set in uppercase letters like this => $_GET
Sidenote: I noticed that you are using the word key in $_GET['key'] etc.
If your other script happens to be using this word as a column reference, you will need to set it inside backticks, since key is a MySQL reserved word. I'm just thinking outloud here.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Plus, I recommend you use mysqli_ functions with prepared statements, or PDO with prepared statements.
I'm trying to convert a previous line I had where I was calling something back from the database, and insert it instead.
This is the function I have, but I can't get the INSERT INTO to work correctly
I've already debugged that: the connection to the DB is working fine, the session var for user is set and that the $avatarID is present.
if(!empty($_SESSION['user'])){
$avatarID = $_POST['avatarID'];
$avatarID = mysql_real_escape_string(trim($_POST['avatarID']));
// Insert into DB
$sql = "INSERT INTO `users` (`avatar`) VALUES ('{$avatarID}') WHERE `username` = '".$_SESSION['user']."'";
$query = mysql_query($sql);
if($query === false){
return false;
}else{
return true;
}
header('Location: profile.php');
}
I think it's an issue with the $sql line. I'm not getting any errors other than a simple blankpage/dead screen.
Attempted changing to just the following:
// Insert into DB
$query = mysql_query("INSERT INTO `user` (`avatar`) VALUES ('{$avatarID}'") or die(mysql_error());
Edit OK so I realise the mistake I have made, as this should be an UPDATE WHERE not INSERT INTO. But I am still struggling to get the query details correct even when using UPDATE and WHERE. But still no result:
<?php session_start();
require 'connect.php';
if(!empty($_SESSION['user'])){
$avatarID = $_POST['avatarID'];
$avatarID = mysql_real_escape_string(trim($_POST['avatarID']));
// Insert into DB
$sql = "UPDATE `users` SET `avatar`='{$avatarID}' WHERE `username` = '".$_SESSION['user']."'";
$query = mysql_query($sql);
if($query === false){
return false;
}else{
return true;
}
header('Location: profile.php');
}else{
header('Location: choose-avatar.php');
}
?>
Use UPDATE instead of INSERT
$sql = "UPDATE `users` SET `avatar`='{$avatarID}' WHERE `username` = '".$_SESSION['user']."'";