Sending content from my frontend to my PHP/MySQL-backend - php

When I send my content from my frontend it successfully reaches my if (!empty)-statement but the table in my phpmyadmin/mysql-database does not recieve the information and does not add it.
I have two tables. One varchar (text) named "photo" and a ID called "id" which is A_I.
With my current code I only send (well attempt to send) the text about "photo" but nothing about the ID as it is A_I? Maybe I need to add some addiotional code to that as well and that might be the issue here and the reason the database does not seem to add the content that I send?
<?php
$value = json_decode(file_get_contents('php://input'));
$mysql_pekare= new mysqli ("", "","", "");
if(!empty($value)) {
echo "You reached the IF-statement";
$stmt = $mysql_pekare->prepare("INSERT INTO photoAlbum(`photo`) VALUES(?)");
$stmt->bind_param("s", $value['photo']);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
}
?>
In my frontend when I send the content I recieve this in the log:
{"photo":"test"}
And I also recieve this in the log, the echo call I did if it reaches the IF function which it successfully does:
"You reached the IF-statement"

By default, json_decode() returns an object, so your value is in $value->photo.
So your INSERT code should be -
if(!empty($value)) {
echo "You reached the IF-statement";
$stmt = $mysql_pekare->prepare("INSERT INTO photoAlbum(`photo`) VALUES(?)");
$stmt->bind_param("s", $value->photo);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
}

you must put the value for mysqli constructor required like localhost or ip , username of database , password of your database and database name then it will work fine for Example:-
$mysql_pekare=new mysqli ("localhost", "username","password", "databasename");

Related

PHP/SQL : "false" value received from database with good query

I have a php script who ask my database with PDO to verify if some values sent exists. If they exists, the database respond with the id of this line's value.
I tested the query on mysql and it works but the value received is false.
This code is only for personal use.
There is the code :
<?php
include("../template/pdo.php");
$query = $pdo->prepare("SELECT id_utilisateur FROM utilisateur
WHERE `mail` IN ( ':mail' )
AND `mdp` IN ( ':mdp' )");
$query->bindParam(':mail', $_GET['identifiant'], PDO::PARAM_STR);
$query->bindParam(':mdp', $_GET['mdp'], PDO::PARAM_STR);
$success = $query->execute();
if($success)
{
$result = $query->fetch();
var_dump($result); //bool(false) actually
if($result == false){
$message = "Try again.";
}
else{
$message = "Congratulation !";
}
}
I tested everything I know :
$_GET is a print/paste from my database table to my url and i have print him
Printed/pasted on phpMyAdmin the query from PDOStatement::debugDumpParams() with my $_GET values
pdo.php work and used on other scripts
No log in my logs files.
Someone can help me ?
Thanks !
If you are testing against a single value use =, not IN.
If you have a list of values, several changes are needed.
The bind code will add quotes, you already have quotes. Remove your quotes.

PHP PDO select entry from database that matches a variable

I've looked at some of the other answers on here regarding this but I keep getting errors so here goes.
Whenver a user visits the site, they are asked to provide their name and are assigned a random integer. When they hit submit to enter their name the form gets submitted and saved to the database and the user gets redirected back to the main page. If the random number once again matches a number saved in the database, that name gets displayed.
I have no problem inserting values into the database but I am having some issues retrieving them back out.
My connection to the database is fine, just left the values generic for the purpose of this question.
<?php
$min=1;
$max=100;
$rand_number = rand($min,$max);
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
//Set PDO Error Mode to Exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL
$stmt = $conn->prepare("select nickname from users where number=".$rand_number);
$stmt->execute();
if (!$stmt) {
foreach($result as $row) {
echo $row['nickname'];
}
}
}
?>
I'm getting an error that something is wrong around the part where I'm matching the query to the variable.
The only thing I really see missing is where you would fetch the data. You can either use one of the fetch* methods of PDOStatement or simply iterate the statement itself (it implements Traversable).
Also, you should use parameter binding.
$stmt = $conn->prepare('SELECT `nickname` FROM `users` WHERE `number` = ?');
$stmt->execute([$rand_number]);
while($nickname = $stmt->fetchColumn()) {
echo $nickname;
}

Trouble dealing with results from a SELECT query with MySQLI

The basic control structure I'm trying to get to work is to query the DB with the username and email, both of which are unique keys, and if either are in the DB let the user know that they have been taken and to please pick something else. The problem I'm running into is getting the result data in a usable form that I can then check the user-supplied data against.
I cut out the prepared statements for insertion from the snippit, as well as the validation routines, since both of them are working fine.
DB connection snippit
try {
if(!($dbc = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME))){ // Creates the $dbc variable object so we can
// have a connection to the database.
// uses mysqli functions.
throw new Exception;
}
}
catch (Exception $e) {
echo '<p>Could not connect to the database. Please contact the system administrator.</p>';
}
Snippit of Registration script
//before this was validation routines, if anything was wrong the script generated something into $reg_errors which is an array.
if(empty($reg_errors))
{
//queries database if there are any matches for username or email from user input.
if($stmt = $dbc->prepare("SELECT `email`, `username` FROM `users` WHERE `email` = ? OR `username` = ?"))
{
$stmt->bind_param("ss", $e, $u);
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows; //gives the number of rows returned from SELECT query. 0 means no dupes, 1 means one record has BOTH email and username, 2 means two different records (one with email, one with username)
##THIS IS WHERE I'M RUNNING INTO TROUBLE GETTING THE DATA IN A USABLE FORM##
$stmt->close();
} else {
echo "<p>Can't talk to database right now. Try again later, please.</p>";
}
if($rows==0) //no dupes of username or email, so let's try and add them into the DB
{
//prepared statement for insertion into DB
//also get's the count of affected rows. 1 means record inserted correctly.
//asks DB if a new row was created, and if so, thanks user for
//registration on the site & sends an email to their email.
//if query doesnt work, an error is triggered
if($count==1) {
//constructs a thank you note and emails it to the user, using the email they supplied.
exit();
} else {
echo "<p>Unable to process your registration at this time. Please try again later..</p>";
}
} else { // both username and email might be already used in DB, and error msgs are generated for array.
if($rows==2) { // this checks to make sure both entries are dupes
$reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link to the right to have your password sent to you.';
$reg_errors['username'] = 'This username has already been registered. Please try another.';
} else { //this checks to see which of the two (email or username) is already in DB if both arent dupes.
if((__NEED SOMETHING HERE FROM DB QUERY___ == $_POST['email']) && (__NEED SOMETHING HERE FROM DB QUERY___ == $_POST['username'])) { //both match entries in DB
$reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link to the right to have your password sent to you.';
$reg_errors['username'] = 'This username has already been registered with this email address. If you have forgotten your password, use the link to the right to have your password sent to you.';
} elseif(__NEED SOMETHING HERE FROM DB QUERY___==$_POST['email']) { // email match
$reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link to the right to have your password sent to you.';
} elseif(__NEED SOMETHING HERE FROM DB QUERY___==$_POST['username']) { // username match
$reg_errors['username'] = 'This username has already been registered. Please try another one.';
}
} // end of $rows==2 ELSE
} // end of $rows == 0 IF
} else { // end of empty reg_errors conditional
//do something if the reg_error array isnt empty..
}
i'm pretty sure the answer lies in iterations and using meta_data from the result mysqli object, but after beating my head against a wall for a couple days and pouring over the mysqli php manual pages like a maniac, I'm still no closer to figuring out what I should be doing. Could anyone point me in the correct direction?
Starting from the registration script, have you tried this:
if($stmt = $dbc->prepare("SELECT `email`, `username` FROM `users` WHERE `email` = ? OR `username` = ?"))
{
$stmt->bind_param("ss", $e, $u);
$stmt->execute();
$stmt->bind_result($email, $username);
$rows = $stmt->num_rows;
//Move Conditionals Up a Little
if( $rows == 0 ) { //If No Records are Found
//Continue Registration
}
else if( $rows == 1 ) { //If One Record is Found
$stmt->fetch();
//Do Something With $email and $username from DB Here
}
else { //If More than One Record is Found
while( $stmt->fetch() ) { //Iterate Through Records
//Do Something With $email and $username from DB Here
}
}
}

PHP/MySQL code fail to insert duplicate row

I have some PHP code to select data from & insert data into a MYSQL database.
Here's what I'm trying to do:
- receive a barcode serial number from a JSON payload
- connect to the MySQL database
- check a database table (passes) to see if the barcode has been registered
- if so, write this barcode + timestamp into another table (activations). Then return a JSON mssage that it was successful
- if not, return a JSON message that the barcode was not yet registered.
The code below works OK when I check a specific barcode for the first time. But after that it doesn't insert a new entry in the activations table. Instead I get the message 'Activation not recorded' ..
Any idea what I'm doing wrong?
Thanks if you can help!
Andrew
<?php
//Messages will be returned as JSON data
header("Content-type: application/json");
//read the POST payload
$payload = json_decode(file_get_contents('php://input'), true);
//get a database connection
require_once("../class/Database.php");
$db = Database::get();
//check for a valid pass
$barcode = $payload['barcode'];
$statement = $db->prepare("SELECT * FROM passes WHERE barcode = ?");
$statement->execute(array($barcode));
$row = $statement->fetch(PDO::FETCH_ASSOC);
if ($row) {
$statement2 = $db->prepare("INSERT INTO activations(activationDatetime, barcode) VALUES (?,?)");
$statement2->execute(array(date("Y-m-d G:i:s"),$barcode));
if ($statement2->rowCount()==0) {
print json_encode(array("msg"=>"Activation not recorded"));
} else {
print json_encode(array("msg"=>"Pass successfully activated"));
}
} else
{
print json_encode(array("msg"=>"Pass not registered"));
exit();
}
flush();
exit();
?>
I guess if ($statement2->rowCount()==0) { this statement is wrong please check. You can not use "rowCount" there as it is a insert query.
And I think, it is inserted only issue is not showing message properly.
You should print the sql error at the debug stage of your page.
I guess, the barcode field is uniq.

mysqli - warning and error

i have this code but i got two errors. I put in the comments the errors
if(!empty($_POST['email']) && validateEmail($email)) {
$email = $_POST["email"];
if ($sql = $db->prepare("select email from users where email=?")) {
$sql->bind_param('s', $email);
$sql->execute();
$sql->bind_result($email);
while ($sql->fetch()) {
$salt = "PiuwrO1#O0rl#+luH1!froe*l?8oEb!iu)_1Xaspi*(sw(^&.laBr~u3i!c?es-l651";
$password = md5($salt . $userExists["email"]);
$pwrurl = "www.yoursite.com/reset_password.php?q=" . $password;
$mailbody = "Dear user,<br><br>If this e-mail does not apply to you please ignore it. It appears that you have requested a password reset at our website www.yoursitehere.com<br>
To reset your password, please click the link below. If you cannot click it, please paste it into your web browser's address bar.<br> <a href='$pwrurl'>$pwrurl</a> <br> <br>
Thanks,\nThe Administration";
$mail->MsgHTML($mailbody);
$mail->AddAddress("dxxb#hotmail.com","Nome da Pessoa");
$mail->IsHTML(true);
if(!$mail->Send()) {
echo "Deu erro: " . $mail->ErrorInfo;
} else {
echo "Enviado com sucesso";
}
}
$sql->close();
$db->close();
}
($sql = $db->prepare('insert into password_reset (code) values (?)')); // Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli in
$sql->bind_param('s', $password); // Fatal error: Call to a member function bind_param() on a non-object
$sql->execute();
$sql->fetch();
$sql->close();
$db->close();
}
all code works fine, but now i need to insert the salt in the db but i can't, and i don't know why
thanks
Edited code to the last version
After you execute a query, fetch returns one result. There may be more -- there may be many, many more -- so you should be calling fetch in a loop to get them all. You aren't supposed to prepare a new query until you've finished dealing with the old one, which would usually mean fetching every row of the result and closeing (in your case) $sql. Otherwise, the database is still in the middle of answering one request when you're trying to issue another one.
The first error says it all - you can't have more than 1 prepared statement/query "in flight" at once. You've not finished fetching data from the first query (select email ...) when you tried to prepare another statement (insert into ...).

Categories