I wrote the following code to retrieve data from the database
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'users';
$con = mysqli_connect($host, $username, $password, $database);
// catch the values that are passed by the POST method
$courseId=$_POST["courseId"];
$hall=$_POST["hall"];
$day=$_POST["day"];
$year=$_POST["year"];
$time=$_POST["time"];
$statement=mysqli_prepare($con,"SELECT * FROM Lectures WHERE day=? AND timeInterval=? AND courseId=? AND hall=? AND year=? ");
mysqli_stmt_bind_param($statement,"sssss",$courseId,$hall,$day,$year,$time);
mysqli_stmt_execute($statement);
// have to collect the results that are coming after the query is being executed
mysqli_stmt_store_result($statement); //storing the results in a buffer for temporary
// now we need to bind the results
mysqli_stmt_bind_result($statement,$day,$time,$courseId,$hall,$year,$noStudents,$courseRefName,$courseRefTelNo,$lecturer);
// to send the data via JSON string
$lectureDetails=array();
mysqli_stmt_fetch($statement);
$lectureDetails["day"]=$day;
$lectureDetails["time"]=$time;
$lectureDetails["courseId"]=$courseId;
$lectureDetails["hall"]=$hall;
$lectureDetails["year"]=$year;
$lectureDetails["noStudents"]=$noStudents;
$lectureDetails["courseRefName"]=$courseRefName;
$lectureDetails["courseRefTelNo"]=$courseRefTelNo;
$lectureDetails["lecturer"]=$lecturer;
// data are stored in the array. now we need to send them via a JSON string
echo json_encode($lectureDetails);
// the java file that calls this method will receive echo
//The PHP json_encode function returns a string, containing the JSON equivalent of the values passed to it
//so in here $lectureDetails array is passed throught throughe JSON String.
mysqli_stmt_close($statement); //closing the connection
mysqli_close($con); //closing the sql connection
?>
according to the working fetching file as below(this returns values as expected)
<?php
//database connection
$host = 'localhost';
$user1 = 'root';
$password1 = '';
$database = 'users';
$con = mysqli_connect($host, $user1, $password1, $database);
//checking the validity of the database
// if(!$con){
//die("connection Failed" . mysqli_connect_error());}
//echo "connected Successfully";
$userName=$_POST["userName"];
$password=$_POST["password"];
$statement=mysqli_prepare($con,"SELECT * FROM usersLogged WHERE userName=? AND password=?");
//to prevent from sql injection
mysqli_stmt_bind_param($statement,"ss",$userName,$password);
mysqli_stmt_execute($statement);
//after executing the command we will get all the results that were selected
mysqli_stmt_store_result($statement); //storing the results in a buffer for temporary
//we need to bind the results
mysqli_stmt_bind_result($statement, $userId, $userName, $firstName, $lastName, $password, $position,$birthDate,$qualification,$email);
//now we need to store them into an array inoder to send them via a JSON
$user=array();
mysqli_stmt_fetch($statement);
//fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result.
//Data are transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance (but reduces memory cost).
//storing the values which are fetched from the database are kept in the array(#user)
$user["userName"]=$userName;
$user["firstName"]=$firstName;
$user["lastName"]=$lastName;
$user["password"]=$password;
$user["position"]=$position;
$user["birthDate"]=$birthDate;
$user["qualification"]=$qualification;
$user["email"]=$email;
//now we need to pass the content to the phone,we send the array in a json
echo json_encode($user); // the java file that calls this method will receive echo
//The PHP json_encode function returns a string, containing the JSON equivalent of the values passed to it
//so in here $user array is passed throught the JSON String.
mysqli_stmt_close($statement);
mysqli_close($con);
?>
but the above php file is not fetching data from the mysql database.
I have created a Lectures table at the current users database and day time courseId hall year courseRefName and lecuturer are of String data type , noStudents and courseRefTelNo are of integer datatype.
Is there any mistake in the mysqli_prepare or in the way this is encoded to JSON, because Iam not getting any return from this (above) php file to my java in android application
I found the problem, it was the mismatch between the data sent via POST and in the database had caused the problem. I have sent time in form of 08.00-10.00 and in database they were as 08-10 in form of 5 digits. So if anyone encounter problems like these be first check the data in the database and the values you passed through POST method
Related
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.
I have tried like this:
$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:
$PartNo = $_POST['ManuPartNo’];
$BikeManufacturer = $_POST['BikeManufacturer’];
$BikeModel = $_POST['BikeModel’];
$BikeType = $_POST['BikeType’];
$BikeWheel = $_POST['BikeWheel’];
$BikeColour = $_POST['BikeColour’];
$BikeSpeed = $_POST['BikeSpeed’];
$BrakeType = $_POST['BrakeType’];
$FrameGender = $_POST['FrameGender’];
$AgeGroup = $_POST['AgeGroup’];
$DistFeatures = $_POST['DistFeatures’];
These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'
I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.
This is all running on a plesk server.
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.
// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Include db.php on every page where queries are executed and perform queries the following way
// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)
$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;
// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();
if($stmt){
echo "Row inserted";
}else{
echo "Error!";
}
See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.
You should try this
$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
If this doesn't work, enable the null property in sql values. So you can find out where the error originated.
I have a loop in which I have to do multiple inserts to the database, it appears that I have to bind the data array every time I get new data and the data changes. I though we could bind once and insert multiple times.
Further research has shown that PDO might be better suited to this task, but I'm curious why its like this with mysqli, and if there is a way to bind array once and execute multiple times.
See comments in code for more detail.
<?php
//usual db stuff
$DBhost = 'localhost';
$DBname = 'test';
$DBuser = '';
$DBpass = '';
//error reporting for mysql
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to database
$conn = new mysqli($DBhost, $DBuser, $DBpass, $DBname);
//prepare this is a dummy table in a dummy database
//actual table is quite complicated
$stmt = $conn->prepare('INSERT INTO `users` (`fname`,`lname`,`city`) VALUES(?,?,?)');
//create a variable to store the data
// so we can bind it before going further
$data=array_fill(0,3,'');
//bind params use array expansion
$stmt->bind_param('sss', ...$data);
//this part runs in a loop
// mock loop for just to show idea
for($i=0;$i<1;$i++)
{
//get the data
$data = get_data();
//already binded $data before the loop
//so execute this should insert the data just returned
//except this doesnt, it inserts blanks
//it acts as if the data still has the blank array from line 20
$stmt->execute();
//bind it again
$stmt->bind_param('sss', ...$data);
//execute
//this inserts the data
$stmt->execute();
}
//mock function to return data the actual function
//returns a multi dimesional array for multiple tables
function get_data()
{
return(array("dinesh","chand","nadi"));
}
any help or ideas highly appreciated
When you run $stmt->execute(); for the first time, inside the for loop, you are executing what you have bind before starting the for loop. So what you have to do is.
Bind what you want $stmt->bind_param('sss', ...$data);
Then execute $stmt->execute();
In your code above, first, remove $stmt->execute(); (first inside the for loop). Then add it after you bind the parameters for the first time(above the for loop). As follows,
Note: What I have changed are marked with ########
<?php
//usual db stuff
$DBhost = 'localhost';
$DBname = 'test';
$DBuser = '';
$DBpass = '';
//error reporting for mysql
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to database
$conn = new mysqli($DBhost, $DBuser, $DBpass, $DBname);
//prepare this is a dummy table in a dummy database
//actual table is quite complicated
$stmt = $conn->prepare('INSERT INTO `users` (`fname`,`lname`,`city`) VALUES(?,?,?)');
//create a variable to store the data
// so we can bind it before going further
$data=array_fill(0,3,'');
//bind params use array expansion
$stmt->bind_param('sss', ...$data);
$stmt->execute(); //########
//this part runs in a loop
// mock loop for just to show idea
for($i=0;$i<1;$i++)
{
//get the data
$data = get_data();
//already binded $data before the loop
//so execute this should insert the data just returned
//except this doesnt, it inserts blanks
//it acts as if the data still has the blank array from line 20
//$stmt->execute(); ########
//bind it again
$stmt->bind_param('sss', ...$data);
//execute
//this inserts the data
$stmt->execute();
}
I currently am trying to store images from an Android application. The app converts the image from the ImageView object into a byte array and then uses Android's built in Base64.encodeToString function so that I could pass it within a HTTP Post Request to my PHP script(which conducts the Insert to Database logic).
For some reason, if in my PHP Script I try to call base64_decode before storing the image as a MEDIUMBLOB, the whole insertion process fails but if I skip the base64_decode within the PHP script, the insertion works successfully. Could anyone explain to me why? Been debugging for hours but can't seem to find out the reason
I was thinking that decoding it would help me save storage space on the DB. I'm aware of not storing images in DBs and using paths and stuff but for my current purpose, I've chosen to store it in the DB as it's much more convenient for me (it's not a huge scalable project as I am just developing something to run for a small study).
Thanks in advance!
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['username']) && isset($_POST['drinkName']) && isset($_POST['caption']) && isset($_POST['photo']) )
{
$username = $_POST['username'];
$drinkName = $_POST['drinkName'];
$caption = $_POST['caption'];
$photoRaw = $_POST['photo'];
$photo = base64_decode($photoRaw);
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO Memories(username, drinkName, caption, photo) VALUES('$username', '$drinkName', '$caption', '$photo')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
What you have described is a problem with how you are trying to insert the raw binary data into the database. When you say it works as base64, that is because base64 generally won't have a single-quote character in it which would break the sql query you show you are using.
To escape the value using those old mysql_* functions, you would use mysql_escape_string...
Please do not use that old mysql method!
You should migrate to mysqli which has been around for many years (your server should support it). Since it looks like your DB_CONNECT method is built around the old mysql, you will have to restructure that for mysqli. Its not too difficult.
I can provide you with an example of how to do the mysqli insert using a safely prepared statement:
$mysqli = new mysqli("localhost", "my_user", "my_password", "db_name");// db connect
$stmt = $mysqli->prepare("INSERT INTO Memories (username, drinkName, caption, photo)
VALUES(?,?,?,?)");
$stmt->bind_param("ssss", $username, $drinkName, $caption, $photo);
$stmt->execute();
This treats the last value as a straight passthrough as a 'string' into your MEDIUMBLOB field to be inserted safely (as well as safely handle the other three variables protecting you from sql injection attacks).
An alternate way to send binary data in, in packets, is this method:
$mysqli = new mysqli("localhost", "my_user", "my_password", "db_name");// db connect
$stmt = $mysqli->prepare("INSERT INTO Memories (username, drinkName, caption, photo)
VALUES(?,?,?,?)");
$null = NULL; // this is just a holder to bind on
$stmt->bind_param("sssb", $username, $drinkName, $caption, $null); // note the 'b'
$stmt->send_long_data(3,$photo); // 3 indicates the 4th bound variable
$stmt->execute();
Some notes:
If your images are bigger than the max_allowed_packet of mysql, you will run into some errors in that regard.
If your field is a BLOB it would only hold an image < 64kb. If its MEDIUMBLOB it will hold a 16mb image, but you risk run over max_allowed_packet.
If you run over the packet issue, you would need to build a packet loop to pass smaller chunks through the send_long_data function.
I've spent most of the day trying to get data from a form into a MySQL Database, everything I have tried so far has not worked, can anyone figure out what is wrong? The database is connecting fine, it just cannot add any data into the mysql database (current errors are at the bottom)
EDIT: Updated Code Below (Still not working!)
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "report"; // Database name
$tbl_name = "tbl_nonconformance"; // Table name
// Connect to server and select database.
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
echo "Database Connected ";
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$tsf = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$sql="INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)
VALUES
('$sno', '$date', '$name', '$email', '$supplier', '$PONum', '$Part', '$Serial', '$TSF', '$Quantity', '$probclass', '$desc')";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
header('Location: ../thankyou.php');
}
else {
echo "ERROR";
}
// close mysql
mysql_close();
?>
First you should change
mysql_connect("$host", "$username", "$password") or die("cannot connect");
to:
$con = mysql_connect($host, $username, $password) or die("cannot connect");
You are calling $con but you never defined it. You want to save your MySQL connection (con) as $con for what you are trying to do here.
You should also really consider upgrading to MySQLi as MySQL is deprecated from PHP and will likely be removed from future versions. Here's a resource to get you started. http://www.php.net/manual/en/book.mysqli.php
Edit July 9 2014: You updated your code, and I do not recall what your original code was. Still, if it's not "working", it's best to describe how it's not working. After you call $result, do this:
if( !$result || !mysql_affected_rows() )
die( mysql_error() );
header('Location: ../thankyou.php'); //this will only occur if there are no SQL errors and the result actually inserted something
mysql_close();
echo "We couldn't forward you automatically. Click here to proceed {insert HTML/JS here}";
This will return the MySQL error message which will help you in your debugging.
You got your argument parsing wrong.
$name = mysql_real_escape_string($con, $_POST['name']);
$con is not defined first of all.
Secondly you are trying to escape $_POST['name'].
mysql_real_escape_string expects 2 arguments, 1st one is mandatory and second one is optional. First argument is the string you want to escape, the second specifies a mysql connection (optional as you may have one open already).
So your statement needs to look like
$name = mysql_real_escape_string($_POST['name']);
Perhaps $con is your mysql connection? Which if it is the case you may want to
$con = mysql_connect ........ and so on
you're using un-secure depreciating methods too. You should research PDO object. It separates variables from your query so they aren't sent at the same time. It also cleans code considerably. I see a few problem areas in his code... You pass in $sno, $date, but they don't exist in your code. $tsf has a different case in instantiation then what you're using in your query. You're using single quotes which can't interpolate data (place values where variable names are). Double quotes do that...
hmmm...
check this out.
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_port = "3306" // Mysql port
$db_name = "report"; // Database name
$dsn = "mysql:dbhost=$host;dbport=$db_port;dbname=$db_name";
//add sno variable declaration here.
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$TSF = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$date = date('d-m-Y');
// Connect to server and select database.
$dbConnect = new PDO($dsn, $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sqlStatement = $dbConnect->prepare("INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)VALUES('?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')");
try{
$sqlStatement->execute(array($sno, $date, $name, $email, $supplier, $PONum, $Part, $Serial, $TSF, $Quantity, $probclass, $desc));
header('Location: ../thankyou.php');
}catch(\PDOException $e){
echo 'Error: Could not connect to db.';
}
?>
PDO object is really easy. create $dbConnect = new PDO(). You see the arguments there. dsn, username, password. The last argument is just an associative array setting PDO's error mode with constants. This allows us to use the try catch block to do error handling. IF PDO can't connect we get the catch block to fire...otherwise the try block which is where our data is sent to the db... You see we have a variable called $sqlStatement.. this is made through $dbConnect->prepare(). This function takes the statement... notice variables are excluded for question marks. Inside the try block we call execute from the statement...this takes and array of values that will replace the question marks in order.
remember to create sno variable. I added date for you. also be sure all cases and spellings are right. One letter in your query string, whether spelled wrong, or even just cased wrong will cause a failure.
let me know if there's any errors or questions. jeremybenson11#gmail.com
This is designed to help me understand what is going on with the query.
It should tell me what values are queried and print them.
It does not pull the userid for some reason, instead saying 0 or null.
It prints:
string(0) "" NULL string(11) "pwdhere" The userid is 0 and the password is pwdhere----oooo set as oooo----6179cbcdc21dd1b3c478e7e2226e0432
Should the session be these 32 characters or the userid/username?
Why is it not pulling userid?
AND WHY DOES IT WORK WHEN THE PASSWORD IS WRONG?
THANKS!!!
<?php
//Store the login in the session:
session_start();
?>
<?php
include ("connectionlinkhere.php");
//connection errors if any...
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//GETTING DATA FROM FORM
$userid = htmlentities($_POST['userid'], ENT_QUOTES);
$password = htmlentities($_POST['password'], ENT_QUOTES);
//create a prepared statement
if ($stmt = $mysqli->prepare("SELECT userid, username, password FROM admins WHERE userid=? and password=?"))
{
// bind parameters-define them...the -iss- is for integer, string, string
$stmt->bind_param("iss", $userid, $username, $password);
//execute...
$stmt->execute();
// bind result variables
$stmt->bind_result($userid, $username, $password);
//fetch value
$stmt->fetch();
//to see what the database query is actually pulling
var_dump($userid, $username, $password);
//tell it to format the query results and then print the sentence
$format = 'The userid is %d and the password is %s';
echo sprintf($format, $userid, $password);
//set session
$_SESSION['userid'] = $_POST['username'];
//just to break up the line
echo "----oooo set as oooo----" ;
//this is the 32 digit session value, although assigned as userid or username
echo session_id();
/* close statement */
$stmt->close();
}
// redirect the user
//header("Location: index.php");
else
{
echo "what are you doing...";
}
/* close connection */
$mysqli->close();
?>
You use bind_param() to replace ? in your query with what you are looking for. You use bind_result() to get the data from your query (which you have done correctly, from what I can see). Put the data you want to search for in bind_param() to replace the ?'s.
Was writing a comment, then realized this may be the issue... Thank you #EdCottrell.