I am trying to make a messaging system for my site. I have this code in my handler php file (which processes the sending of msg):
if($actions=="verstuur"){
//read variables
$naar = $_POST['naar'];//varchar in database. the post = 'ikdekker
$van = $username;//varchar in database. the username = 'user1'
$status = "0";//int in database
if ($_POST['admin'] != ""){
$admin = $_POST['admin'];}else{
$admin=2; //int in database. the post = '0 or 1'
}
$onderwerp = $_POST['onderwerp'];//varchar in database. the post = 'example'
$bericht = $_POST['berichtl'];//varchar in database. the post = 'example message'
$tijd=date("Y-m-d H:i:s");//timestamp in database. the post = '2014-18-1 20:20:20'
// enter is enter
$bericht=nl2br($bericht);
$bericht=eregi_replace("\n","",$bericht);
mysql_query($conn, "INSERT INTO pm (van,naar,status,admin,onderwerp,tijd,bericht) VALUES ('$van','$naar','$status','$admin', '$onderwerp','$tijd','$bericht')");
echo"<script>";
echo"alert('". $actions . "');";
echo "</script>";
}
but it keeps giving me this error:
Warning: mysql_query() expects parameter 1 to be string, resource given in /home/deb70377/domains/cowboycombat.nl/public_html/misc/php/pm_verwerk.php on line 34
cant figure it out, I normally do the html..
You should not use mysql* functions as they are deprecated. Use mysqli* ones:
mysqli_query($conn, "INSERT INTO pm (van,naar,status,admin,onderwerp,tijd,bericht) VALUES ('$van','$naar','$status','$admin', '$onderwerp','$tijd','$bericht')");
Also consider using prepared statements http://lt1.php.net/pdo.prepared-statements
UPADTE
to get the $conn variable you write:
$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
Query first, then the $conn variable
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.
Hello there am trying to insert data into MSSQL using PHP. I have tried many times to figure out what the problem might be but i seem not to find it. Is there something am not getting right or missing?
<?php
//pull form fields into php variables
$no = $_POST['no'];
$name= $_POST['name'];
$date = $_POST['date'];
$leave = $_POST['leave'];
$days= $_POST['days'];
$empno= $_POST['empno'];
//connect to sql
$dbc = mssql_connect('Server-PC','user','password','database')or die('Error connecting to
the SQL Server database.');
// Input into staff database
$query = "INSERT INTO dbo.[CAGD$Leave Plan] ([No_],[Employee No_],[Employee Name],
[Leave Name], [Start Date],[Leave Days],Satus) VALUES
('$no','$name','$leave','$date','days','empno')";
$r esult = mssql_query($query,$dbc)or die('Error querying MSSQL database');
//close to sql
mssql_close($dbc);
echo $name . 'Your submission has been received<br />';
echo 'If you need change this request please contact your HR Manager<br />';
echo 'Thank you <br />';
echo 'HR Manager';
?>
I get this error message:
Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'dbo.CAGD Plan'.
(severity 16) in C:\xampp\htdocs\CAGD\leave_request.php on line 110
Warning: mssql_query() [function.mssql-query]: Query failed in C:\xampp\htdocs
\CAGD\leave_request.php on line 110
Error querying MSSQL database
You can use SQLSRV Driver instead of MSSQL Driver and then try this
<?php
$serverName = "serverName";
$options = array( "UID" => "sa", "PWD" => "Password", "Database" => "DBname");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$no = $_POST['no'];
$name= $_POST['name'];
$query = "INSERT INTO dbo.Test
(No_,FirstName)
VALUES(?, ?)";
$params1 = array($no,$name);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
This is more useful, and you can learn more here:
https://msdn.microsoft.com/en-us/library/cc626305(v=sql.105).aspx
First Specify your database Connection...
mssql_connect('Server-PC','user','password','database')
like -> "localhost","root","XXXX", "DBNAME"
then query like
$query = "INSERT INTO TABLENAME (id,name) VALUES
('$id','$name')";
$result = mssql_query($query,$dbc)
Hmm, it seems to me that you have 7 fields in the table but only 6 values submitted - you are missing the value for the first column, [No_].
Besides, the last column satus (i suppose it should be 'status') does not have de [] delimiters.
The error returned tells you that the name of the table is wrong.
And yes variable names are case sensitive in PHP, it should be $leave - best to exit the string and concatenate - something like "bla bla".$leave."anything here with spaces or not" .
Is this supposed to be a variable?
$query = "INSERT INTO dbo.[CAGD$Leave Plan] ([No_],[Employee No
^^^^^^
If so, then it's apparently undefined in your code, and the generated query string will contain dbo.[CAGD Plan], and not whatever value was supposed to be in that variable. If the $ is literally in your table name, then it should be CAGD\$Leave, so that $Leave isn't treated as a variable.
I've recently been working on a uni assignment and had a lot of trouble getting my code to work.
The errors that seem to occur when I upload my .php file onto the server and then try to view them are the following:
Warning: oci_parse() expects parameter 1 to be resource, string given in /home/contactusphp.php on line 227
Warning: ociexecute() expects parameter 1 to be resource, null given in /home/contactusphp.php on line 232
Your mesage has been sent successfully!
Additional details:
This is for use in an Oracle database, and the original purpose was for a user to use a contact form to send a message to the site owner (putting the message into the database).
My code is as follows:
211. <?
212. // extract form data
213. $emailcontact = $_REQUEST['emailcontact'] ;
214. $email_address = $_REQUEST['email_address'] ;
215.
216. // Create the SQL statement to add data into the database
217. $sql = "INSERT INTO contactus (emailcontact, email_address) VALUES ('$emailcontact', '$email_address')";
218.
219. // Set the oracle user login and password info
220. $dbuser = 'XXXX';
221. $dbpass = 'XXXX';
222. $db = 'SSID';
223. $connect = 'OCI_Logon($dbuser, $dbpass, $db)';
224.
225.
226. // Add this data into the database as a new record
227. $stmt = OCI_Parse($connect, $sql);
228. if(!stmt) {
229. echo 'An error occurred in parsing the SQL string./n';
230. exit;
231. }
232. OCI_Execute($stmt); {
233. echo ('Your mesage has been sent successfully!');
234. }
235. ?>
I can't seem to find what could be wrong, and I'm not very experienced with web development either.
EDIT: I got rid of quotes, and changed OCI_Logon/OCI_Parse/OCI_Execute to OCILogon, etc.
However, the problem changed when I did so.
There's a new error code, which is as follows:
Warning: ociexecute() [function.ociexecute]: ORA-00904: "EMAILCONTACT": invalid identifier in /home/contactusphp.php on line 232
The new code is:
211. <?
212. // extract form data
213. $emailcontact = $_REQUEST['emailcontact'] ;
214. $email_address = $_REQUEST['email_address'] ;
215.
216. // Create the SQL statement to add data into the database
217. $sql = "INSERT INTO contactus (emailcontact, email_address) VALUES ('$emailcontact', '$email_address')";
218.
219. // Set the oracle user login and password info
220. $dbuser = 'XXXX';
221. $dbpass = 'XXXX';
222. $db = 'SSID';
223. $connect = OCILogon($dbuser, $dbpass, $db);
224.
225.
226. // Add this data into the database as a new record
227. $stmt = OCIParse($connect, $sql);
228. if(!stmt) {
229. echo 'An error occurred in parsing the SQL string./n';
230. exit;
231. }
232. OCIExecute($stmt); {
233. echo ('Your mesage has been sent successfully!');
234. }
235. ?>
EDIT:
The problem ended up fixing itself, and I have no idea how.
Why the quotes around this function?
$connect = 'OCI_Logon($dbuser, $dbpass, $db)';
I am retrieving data from a database in android so created a php file as below.
<?php
$db_host = "localhost";
$db_uid = "root";
$db_pass = "";
$db_name = "abc";
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$sql = "SELECT * FROM people WHERE birthyear > '". $_POST["birthyear"]."'";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Now when i run it in the browser as localhost/script.php
error is thrown and the output is displayed as below
Notice: Undefined index: birthyear in C:\xampp\htdocs\jasonscript.php on line 14
[{"id":"1","name":"m","sex":"1","birthyear":"1989"},{"id":"2","name":"a","sex":"1","birthyear":"1986"},{"id":"3","name":"b","sex":"0","birthyear":"1986"}]
Please tell me how to correct my code.
$output[]=array("key"=>$row['field_name'],"key1"=>$row['field_name2']);
store array like this
You are directly inserting $_POST["birthyear"] in your query which makes you vulnerable to SQL injection. Stop doing it right now!
That is also why you get the error. When you directly call the script in your browser, that will be with a GET request and there wont be any POST variables available. So your $_POST array wont have a key for birthyear and thus it warns you about it.
You should start with something like
<?php
$by = isset($_POST["birthyear"]) ? $_POST["birthyear"] : "";
if (empty($by)) {
echo 'Invalid birthyear';
exit;
}
//SANITIZE YOUR BIRTHYEAR HERE
//in this case, probaly check for a integer between 1900 and 2100 or something.
//Although just an int could be enough to prevent injection
if (!is_int($by)) {
echo 'You failed to provide a valid year';
exit;
}
$sql = "SELECT * FROM people WHERE birthyear > '". $by."'";
//execute the code
?>
Although the above code is safe, you should check out bound parameters like used in mysqli prepared statements or PDO
you probably failed to send the values trough post properly.
try print_r($_POST); to see what you are actually sending
you still get all results because every year is > ''
I'm setting up a blog type page for my business. Brand new to MySQL and PHP. Set up this login system. For some reason have no idea why the login is dropping. Suppose to check for errors then return 'good' through php if the email and password is right. If php returns good then it's suppose to redirect to the blog page.
Been dealing with this for a few months need desperate help please. Thank you.
Here is the php code that goes along with the jquery.
Link to test site is here.
test.toddprod.com/login
Would really appreciated the help.
Thanks
<?php
#fake mysql connection first
DEFINE ('DB_USER','usernamegoeshere');
DEFINE ('DB_PASSWORD','passwordhere');
DEFINE ('DB_HOST','hostnamehere');
DEFINE ('DB_NAME','andtheotherthinghere');
$dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
$db = mysql_select_db(DB_NAME, $dbc) or die('Could not select database.'.mysql_error());
$e = $_POST['email'];
$pass = $_POST['pass'];
$q = 'SELECT user_id from toddprod where email="'.$e.'" and pass= SHA1("'.$pass.'")';
$r = mysql_query($db, $q);
if( mysql_num_rows($r)==1 ){
setcookie ( 'user_id', $r);
setcookie ( 'email', '$e');
setcookie ( 'logged-in', 'true');
echo 'good';
}
else if (mysql_num_rows($r)==0) {
echo 'Your '.$e.' with password '.$pass;
};
mysql_close ($db);
?>
Umm there's a number of things I see wrong here...
First of all your query should be sanitized...
$email = mysql_real_escape_string ($_POST['email']); // escape the email
$pass = SHA1(mysql_real_escape_string ($_POST['pass'])); // escape and encrypt the pass
// now you can put it into the query safely
$query = "SELECT user_id from toddprod where email = '$email' and pass = '$pass' ";
Next you're executing the query wrong, the mysql_query function takes two arguments, the query and the database connection. You're passing the wrong arguments, you're passing the query and the result of the mysql_select_db function which is just a boolean value. So you have to $dbc not $db into that query, and even then you're passing the arguments in the wrong order. The query goes first, than the connection. So it should be...
$result = mysql_query($query, $dbc);
Next you're trying to set the return value from the mysql_query function as your cookie but that value is a resource, not the userid that you need. You have to actually read the value from the resource like this.
$row = mysql_fetch_array($result);
$userid = $row["user_id"];
setcookie('user_id', $userid);
Moving on... when you're setting the email cookie, you have the variable in single quotes, so the cookie will actually contain $e and not the actual email because single quotes store strings litterly (without parsing the variables). So you should either use double quotes, or no quotes at all. So either one of the following is fine...
setcookie('email', "$e");
setcookie('email', $e);
Last but not least, you should not have the semicolon at the end of your if-statement, and you again you need to pass the connection not the database-selection result into the mysql_close function, so it should be
mysql_close($dbc);
There, hope this gets you somewhere, try out these changes and if the problem persists i'd be happy to help you further.
Here are links that will help you out:
http://www.php.net/manual/en/function.mysql-query.php
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit:
Here, I have fixed the code according to the problems I found. Try it out, I could not test it so it might have some small syntax errors here and there, but it should give you something to compare with. Also for the future, I would suggest that you name your variables semantically/properly so it's easier for others to pickup and it will also keep you from getting confused like you were passing $db instead of $dbc into a few of your functions.
<?php
// keep the function names in lowercase, no reason, just looks better to me
define('DB_USER', 'usernamegoeshere');
define('DB_PASSWORD', 'passwordhere');
define('DB_HOST', 'hostnamehere');
define('DB_NAME', 'andtheotherthinghere');
// connect to the mysql server
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
// select the database, you don't need to store the result, it just returns true or false
mysql_select_db(DB_NAME, $conn) or die('Could not select database.' .mysql_error());
// escape the input
$email = mysql_real_escape_string($_POST['email']);
$pass = sha1(mysql_real_escape_string($_POST['pass']));
// create the query
$query = "SELECT user_id FROM toddprod WHERE email = '$email' AND pass = '$pass'";
// execute the query
$result = mysql_query($query, $conn);
$usercount = mysql_num_rows($result);
if($usercount == 1){
// read the results and get the user_id
$row = mysql_fetch_array($result);
$userid = $row['user_id'];
// set the cookies
setcookie('user_id', $userid);
setcookie('email', $email);
setcookie('logged-in', 'true');
// echo success message
echo 'good';
}elseif($usercount == 0) {
echo "You're $email with password $pass";
}
mysql_close($conn);
?>
First things first, you MUST sanitise user input with mysql_real_escape_string():
$e = mysql_real_escape_string ($_POST['email']);
$pass = mysql_real_escape_string ($_POST['pass']);
Read up a bit on SQL injection, you'll be very glad you did.
As for the main problem, could you provide a bit more context? How are you checking to see if the user is logged in?