whats wrong with this part of php code? - php

first I have a login form in c# that asks the user to input his email and password then these are data are sent to the domain then I retrieve it in php so I wrote a sql query to get the logged in user id and this works fine till the
if(isset($_POST['y']))
inside of it there is an insert query this query works but doesn't insert the user id ! I tried to figure it out but I dont know whats the problem .
here's the code :
<?php
session_start();
$con = mysqli_connect("mysql7.000webhost.com","a1945567_host","12345678ab","a1945567_db");
$sql = "SELECT ID FROM user WHERE Email = '".$_GET["txt_UserName"]."'AND Password = '".sha1($_GET["txt_Password"])."'";
$result = $con->query($sql);
$
$row = mysqli_fetch_array($result,MYSQLI_NUM);
$_SESSION['ID'] = $row[0] ;
echo "SUCCESS";
echo $usrID = $row[0];
if(isset($_POST['y'])){
$sql = "INSERT INTO `question13_interaction` (uid,no_0,no_1) VALUES ('".$usrID."','".$_POST['y']."',0)";
$con->query($sql);
// mysqli_query($con,$sql);
}
else if(isset($_POST["z"])){
//$sumcount = "INSERT INTO question13_interaction (sumcount)";
//$result = mysqli_query($con,$sumcount);
$sql1 = "INSERT INTO question13_interaction(uid,no_1,no_0) VALUES('".$row[0]."','".$_POST["z"]."',0)";
mysqli_query($con,$sql1);
}
//}
/*else
{
echo "FAILED";
}*/
?>

you have an extra"$" in the code:
$result = $con->query($sql);
$
probably should just be :
$result = $con->query($sql);
also I don;t think you want the echo in this statement - it will probably not set it to the correct value for your query:
echo $usrID = $row[0];
should be
$usrID = $row[0];

Except for the redundant "$", there is another question. There should be a white space between single quote and "AND", or mysql cann't parse the query correctly

Related

Need help inserting info into the database and returning it back

In my code I had three radio buttons that user click to choose the color of each title, text and button that is in hex value. And it is sending info properly, but when the code running that puts everything into the database it's sending user to the to the home page saying that color had been changed, but it did not.
Here's my php code:
session_start();
if (isset($_SESSION['username'])) {
include 'databaseconnection.php';
$username = $_SESSION['username'];
$titlecolor = $_POST['titlecolor'];
$textcolor= $_POST['textcolor'];
$buttoncolor = $_POST['buttoncolor'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: index.php?wronghappened");
exit();
}
else {
if ($row = mysqli_fetch_assoc($result)) {
$update = "UPDATE students (titlecolor, `textcolor`, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
$_SESSION['id'] = $row['id'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['email'] = $row['email'];
$_SESSION['username'] = $row['username'];
$_SESSION['text'] = $row['text'];
$_SESSION['title'] = $row['title'];
$_SESSION['button'] = $row['button'];
header("Location: home.php?color_changed");
exit();
}
}
}
else {
header("Location: index.php?not_in");
exit();
}
You are not using the update query. Excute your update query so it will update the db.
$update = "UPDATE students (titlecolor, `textcolor`, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
mysql_query($update);
Instead of
$update = "UPDATE students (titlecolor, `textcolor`, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
The variable textcolor is being sent to the server as a string, not a variable because you have wrapped it in qoutes. You should only wrap qoutes around strings to be sent as values. Use this instead:
$update = "UPDATE students (titlecolor, textcolor, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
Then to execute this code, run
mysql_query($con, $update);
Replace your query with this:
$updatequery = "UPDATE students set titlecolor='$titlecolor', textcolor='$textcolor', buttoncolor='$buttoncolor' WHERE uname='$uname'";
Now Check that is query successfully executed ?
if (mysqli_query($con, $updatequery))
{
echo "successfully execute.....";
//do something here
}
else
{
echo "Sorry query can't executed!";
echo "My Query ".$updatequery;
}
If query not execute then you will see your query after "My Query ", So copy that query and execute it in your mysql then you will find main error.
Try this
$update = "UPDATE students SET titlecolor='$titlecolor', textcolor='$textcolor', buttoncolor='$buttoncolor' WHERE uname='$uname'";
$updateResult = mysqli_query($con, $update);
instead of
$update = "UPDATE students (titlecolor, `textcolor`, buttoncolor) VALUES (`$titlecolor`, `$textcolor`, `$buttoncolor`) WHERE uname='$uname'";
If your will not execute your query using mysqli_query then it won't show any effect.
Also I will like to suggest you to use PDO in the future instead of mysqli. For this reasons.
Happy Coding :)

How do I loop through the update query in php and display it so it is like a log history

<?php
include('core/init.php');//database connection
if(isset($_POST['btn_submit'])){
$sqlQuery = mysql_query("UPDATE `position` SET `ATR`='".mysql_real_escape_string($_POST['ATR'])."',
$resultQuery = mysql_query($connection, $sqlQuery) or die (mysql_error($connection));
if(mysql_affected_rows($resultQuery) > 0){
echo "updated";
}else{
echo "failed";
}
header('Location:position2.php');
$result = mysql_query("SELECT * FROM position WHERE ID='" .$_POST["id"]. "'");
$row2 = mysql_fetch_array($result);
}
?>
//What this code does it it updates the database based on user input and I am trying to loop through each of the user input as update and display but it doesn't seem to work
($_POST['ATR'])."',
Is missing a closing "
Also formatting code makes it easier to read and debug.

deleting records from mysql table

Continuing with my simple CRUD, I'm stuck again...
So I have a table created called "usuaris" and a column called "id" which is my auto-increment and then another column called "usuari_nom". Now, I want to add "delete function", so when I am displaying the records of my table I've added a to delete it:
<div id="main">
<?php
global $conn;
$query = "SELECT * FROM usuaris";
if($grup_usuaris = mysqli_query($conn, $query)) {
echo "<table>";
echo "<tr><th>Usuaris</th><th>Accions</th></tr>";
while($row = mysqli_fetch_assoc($grup_usuaris)) {
echo "<tr><td>" . $row['usuari_nom'] . "</td><td>Eliminar usuari</td></tr>";
}
echo "</table>";
echo "+ Afegeix Usuari";
mysqli_free_result($grup_usuaris);
} else {
echo "query failed";
echo("Error description: " . mysqli_error($conn));
}
?>
</div>
So now, If I click on "eliminar usuari" it goes to the file where I am adding the query to delete, plus the id of that user; for example: "http://localhost/calendario/elimina_usuari.php?subject=6". But then, in the file elimina_usuari.php, how do I select the id to know what record to delete?
I've thought with $_GET but it doesn't seems to work, either with $_POST:
elimina_usuari.php
<?php
global $conn;
$usuari_id = $_GET['id'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
Any clue how can I get its id? Should I take it from the url somehow?
Thanks
you're doing fine.
just need to change this
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
as you're setting subject instead of id in your url
http://localhost/calendario/elimina_usuari.php?subject=6
^
and if you want to process id, like $_GET['id'], you need to change URL.
"http://localhost/calendario/elimina_usuari.php?id=6"
^ change here
EDIT
as per your comment,
you can use any $variable to $_POST or $_GET, it has nothing to do with the database column name.
Like you can use following.
"http://localhost/calendario/elimina_usuari.php?eve_mf=6"
and on elimina_usuari.php page,
$id = $_GET['eve_mf'];
and second part, why can I do that and I don't need to call it id as it is called in my db table?
Again, it's not the issue what you call variables in you local environment, all you to do(and should take care of) is to put right parameters in your sql query.
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
Here id is the name of your column name in your database. You can't change it here if you even want it to.
however, $usuari_id is your local variable, and you can change it whatever you want.
Hope I've explained what you're looking for :)
You can get the id with $_GET['subject'].
Please be aware about SQL injection as you are wrongly get the id of the user to be deleted:
$usuari_id = mysqli_real_escape_string($conn, $_GET['subject']);
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
You just need to Get the exact variable name or parameter name which you have sent with your url
I mean see your url contains subject=6
that means you have to get subject instead of id;
please replace this code
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
try this in elimina_usurai.php
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>

PHP How to check if a string already exists in a MySQL table

I'm having a user enter a desired name, then check the database to see if it exists before I make it. It's not working properly though, sometimes it echos the right thing, sometimes not.
$makeName = $_POST["userName"];
$nameFind = "SELECT userName FROM usertable WHERE userName = $makeName";
$nameCompare = mysqli_query($con, $nameFind);
if($nameCompare == false)
{
echo "This is a new name";
}
else
{
echo "Pick a new name please";
}
The query doesn't fail just because it returns no rows. Use mysqli_num_rows() to find out if there was a match or not.
Also xkcd
Don't do it that way.
Instead,
Create a unique constraint on the column "username".
Insert the user's desired name.
Trap the error when the desired name already exists.
Why? Your approach always requires two round-trips to the database, and it doesn't account for errors. And you have to trap errors anyway; there are lots of things that can go wrong with an insert statement.
Use quotes and escaping:
"select userName FROM usertable WHERE userName = '" . mysqli_real_escape_string($makeName) . "'"
And then use mysqli_num_rows()
$result = mysqli_query($query); $num_rows = mysqli_num_rows($result);
if(mysqli_num_rows($nameCompare))
{
echo "Pick a new name please";
}
else
{
echo "This is a new name";
}
this will check the result, if there is a row, it's already used.
You need two queries for that anyways
$username = mysqli_real_escape_string($con,$username);
$query = "SELECT * FROM tbl_login WHERE username='$username'";
$result = mysqli_query($con,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 ) {
echo 'false';
}
else{
$query_insert = "INSERT INTO login (username, password)VALUES ('$username','$password');";
$result = mysqli_query($con,$query_insert) or die(mysqli_error());
}

Creating a variable by pulling a value from a MySQL database

I am using a MySQL table called "login" that includes fields called "username" and "subcheckr."
I would like to run a PHP query to create a new variable equal to "subcheckr" in the table where "username" equals a variable called $u. Let's say I want to call the variable "$variable."
How can I do this? The query below is what I have so far.
Thanks in advance,
John
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
I don't know if I understood correctly but if:
Just do something like this.
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
In case you don't know, your query is vulnerable for SQL injections. Use something like mysql_real_escape() to filter your $u variable.
Is this what youa re looking for?
$result = mysql_query($sqlStremail);
$row = mysql_fetch_assoc($result);
$subcheckr = $row['subcheckr'];
$sqlStremail = mysql_query("SELECT subcheckr FROM login WHERE username = '$u'");
$result= mysql_fetch_array($sqlStremail);
$some_variable = $result['subcheckr']; // the value you want
You can do:
// make sure you use mysql_real_escape to escape your username.
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
// run the query.
$result = mysql_query($sqlStremail );
// See if the query ran. If not print the cause of err and exit.
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
// if query ran fine..fetch the result row.
$row = mysql_fetch_row($result);
// extract the field you want.
$subcheckr = $row['subcheckr'];
You can write
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
$result = mysql_query($sqlStremail );
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$row = mysql_fetch_row($result);
$subcheckr = $row['subcheckr'];
$variable = array_pop(mysql_fetch_row(mysql_query("SELECT subcheckr FROM login WHERE username = '$u'")));
Only if username is unique

Categories