Non object error when using prepared statement - php

I have a table containing columns person and person_initials. When Submit is clicked I would like to insert the name in the input box into the person column in the table of names where the initial equals the initial defined. In this case only 1 row containing "I" in the person_initial column exists in the table.
Please see the code below. I'm sure there must be a basic syntax error in the prepared statement but I can't see it. Apologies for the ignorance.
index.php:
<html>
<body>
<form method="post">
Insert: <input type="text" name="q" value="Tim"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$test_name = $_POST['q'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "personnames";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$people = 'I';
$stmt = $conn->prepare("INSERT INTO names (person) VALUE=(?) where
person_initial=(?)");
$stmt->bind_param("ss",$test_name,$people);
$stmt->execute();
$stmt->close();
$conn->close();
}
?>
</body>
</html>

You seem to attempting an update, in which case the syntax would be:
$stmt = $conn->prepare("UPDATE names SET person=? where person_initial=?");

Your INSERT query is wrong. Use
$stmt = $conn->prepare("INSERT INTO names (person) VALUES(?)");
instead
$stmt = $conn->prepare("INSERT INTO names (person) VALUE=(?) where
person_initial=(?)");
If you want to update, then use update query like this
$stmt = $conn->prepare("UPDATE names SET person=? where person_initial=?");

Related

Can I run a sql query in another file?

I am busy with a school project to learn MVC. But I know very little of php.
I have an dbconnection file and it looks like this
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "filmopdrachtdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connet_error);
}
echo "Connected SuccessFully";
I have a login page that looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="../Controllers/UserController.php" method="post">
Gebruikersnaam <input type="text" name="naam">
Wachtwoord <input type="password" name="wachtwoord">
<input type="submit" value="Login">
</form>
</body>
</html>
And I have an User Controller that looks like this:
<?php
include_once ("../Includes/DbConnection.php");
include_once ("../Models/User.php");
$gebruiker = new User();
$naam = $gebruiker->setGebruikersnaam($_POST["naam"]);
$wachtwoord = $gebruiker->setWachtwoord($_POST["wachtwoord"]);
$stmt = "SELECT gebruikersnaam, wachtwoord FROM klanten";
var_dump($stmt);
How do I run the $stmt query. I don't understand what I have to do
$stmt = "SELECT gebruikersnaam, wachtwoord FROM klanten";
EDIT: I want the query $stmt to run in the UserController. Not in the DbConnection file.
If you use stm, you can execute with that code:
$stmt=$conn->prepare("SELECT gebruikersnaam, wachtwoord FROM klanten WHERE user=?");
$stmt->bind_param('s',$naam);
$stmt->execute();
OR
$conn->query($stmt);
In your DbConnection.php file you have a $conn variable which contains your connection to the database. From that variable you can execute your queries on the database.
From the mysqli PHP documentation, modified to work with your code:
$results = $conn->query($stmt);
Please note that this method should not be used with a dynamically generated query string:
//BAD practice, leads to SQL injection
$results = $conn->query("SELECT * FROM MyTable WHERE myColumn = $search LIMIT 10");
For dynamically generated queries use prepared queries.
I could also suggest to use PDO which is a more versatile database interaction libraray in PHP, which you will probably not be able to do for that code as it is for school, but for your own projects :)

I'm trying to make a click counter using PHP and mysql

<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$db_name = 'somedb';
$conn = mysqli_connect($hostname, $username, $password, $db_name);
if (isset($_POST['abc'])){
$date_today = date('Y-m-d');
$somecount=("INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', '') ON DUPLICATE KEY UPDATE somecount=somecount+1");
mysqli_query($conn, $somecount);
}
?>
<form method="post" action="some.php">
<input type="submit" name="abc">
</form>
I've tried this code. Someone please help me out to count the click made by the user on a button or submit input tag. Thanks in advance.
Just update this line:
From
$somecount=("INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', '') ON DUPLICATE KEY UPDATE somecount=somecount+1");
to
$somecount=("INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', '1') ON DUPLICATE KEY UPDATE somecount=somecount+1");
also, to make sure you are not redirecting to another page that the current page itself do the below code:
<form method="post" action="">
<input type="submit" name="abc">
</form>
doing so will make sure that you will submit to the same page.
I would suggest avoiding ON DUPLICATE KEY UPDATE and instead use a little bit different logic:
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$db_name = 'somedb';
$conn = mysqli_connect($hostname, $username, $password, $db_name);
if (isset($_POST['abc'])){
$date_today = date('Y-m-d');
$selectStatement = "SELECT somecount FROM sometable WHERE today = '".$date_today."'";
$selectResult = mysqli_query($conn, $selectStatemnt);
$finalStatement = "";
if($selectResult){
$finalStatement = "UPDATE sometable SET somecount = somecount + 1 WHERE today = '".$date_today."'";
}
else{
$finalStatement = "INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', 1)";
}
mysqli_query($conn, $finalStatement);
}
?>
<form method="post" action="some.php">
<input type="submit" name="abc">
</form>
Here we first check if the row for today already exists in the table. If so simply increment it else create a row and set the count value to one.

how to include a php variable as part of a table name?

I have a site where I needed to use separate table names for each of my clients because the data has to be updated all the time with a manual import.
example:
kansas_users
newyork_users
I have set a global variable as $client which will create the state name on all pages so if I echo "$client"; then I will see "kansas" for example on any page.
I would like to include this variable as part of my SQL query if possible to make it easier to code:
SELECT "nick, firstname, lastname, cell
FROM database.$client_members
where active =1 and id = $user->id";
Is this possible or even safe to do?
Yes it possible you can do some thing like below
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = 'kansas';
$table_name = "database." . $conn->real_escape_string($client) . "_members";
$query = sprintf("SELECT nick, firstname, lastname, cell
FROM %s WHERE active = 1 and id = ?", $table_name);
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user->id);
But i think you should seriously consider normalizing your database to avoid such issues

Insert into SQL database user input from HTML form

I am trying to insert into column "UserId" in my sql database, using php, text that the user inputs in the HTML form.
Below is a basic example to help me figure out what I am doing wrong.
HTML
<html>
<form action="index1.php" method ="post" name="trial">
<input type="text" name="testName" id="testId">
<br>
<input type="submit" value="Submit">
</form>
</html>
PHP
$servername = "localhost";
$username = "root";
$password = "xx";
$dbname = "wp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Some notes:
I can connect to database and insert in the correct columns checkbox and radio values from the form
I cannot find a way to insert in the database the user text input from the form (UserProfile is the table and UserId the column).
Would using a javascript variable, like below one, help?
var testVar = document.getElementById("testId").value;
I know I am opening myself to hacking using the above code, I would like to improve it later on but I think I need to first figure out the basics (ie: how to get the user text input added to the database)
Than you in advance for any help!
you are storing the value in $UserId, not in $testName:
Change your SQL Query to
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
I think this will help.
BTW: Think about SQL-Injection! Look here: How can I prevent SQL injection in PHP?
Look here
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
Change $testName to $UserId in sql statement because it's the name of your new variable in php:
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
But I advice you to:
1- use PDO for any sql handling in php
2- use mysqli_real_escape_string to protect your code from threats.
make it like:
$UserId = mysqli_real_escape_string($con, $_POST['testName']);

Mysqli and PHP not sending data [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I'm building a recruiting website and need to save user data in my database but my form isn't sending anything to the database in phpmyadmin (using WAMP).
I checked the error logs for PHP, MySQL and Apache but don't see any errors. I also added "if/echo" blocks inside the $conn variables to test the connection, which returned true. Code below.
<!-- index.html-->
<form action="process.php" method="post">
<input type="text" name="first_name" placeholder="First Name" /><br/>
<input type="text" name="last_name" placeholder="Last Name" /><br/>
<button type="submit" name="submit"></button>
</form>
//database.php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "xxxx";
$dberror1 = "Could not connect to the database!";
$dberror2 = "Could not find selected table!";
// Connection to the database, Already tried this with echo statement and works
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
// Selecting the database to connect to
$select_db = mysqli_select_db($conn, 'mainbase') or die ($dberror2);
//process.php
<?php include 'database.php';
if(isset($_POST['submit'])) {
// Creating variables to store form values
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
//Executing the query
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name') //Values in 'candidates' table on phpmyadmin
VALUES ('$first_name','$last_name')");/*variables from above*/
}
You're using myqli incorrectly. But on top of that, use PDO to connect to your database instead. It's safer and easy to expand in the future. Here is an example of how to connect to your database with PDO.
<?php
$myUser = "XXXXXX";
$myPass = "XXXXXX";
try{
$dbPDO = new PDO('mysql:host=localhost;dbname=xxxxxxxx', $myUser, $myPass);
$dbPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection was successful";
} catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br />";
die();
}
?>
Simply change the Xs to your server's settings.
When you want to start a query simply you can do it like so:
$query = $dbPDO->prepare("SELECT * FROM Table_Name");
$query->execute();
Of course you'd want to pass variables to your queries so you can do that like this:
$query = $dbPDO->prepare("SELECT * FROM Table_Name WHERE ID = :id");
$query->bindParam(':id', $id);
$query->execute();
That keeps SQL injection off your worries. Just make sure to sanitize your variables before binding them to the query as well.
I figured I'd show how to insert your variables into your table with PDO.
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (:fname, :lname)");
$query->bindParam(':fname', $firstName);
$query->bindParam(':lname', $lastName);
$query->execute();
You could also make an array of both of your POST variables and pass that instead of binding each variable at a time.
$candidateName = array('$_POST['first_name']', '$_POST['last_name']');
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (?, ?)");
$query->execute($candidateName);
I hope that helps!
Happy coding!
The problem
Don't put table name and column names between apostrophes. That's what's causing your query to fail. Apostrophes are used to pass strings.
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name')
VALUES ('$first_name','$last_name')");
Should be
mysqli_query($conn, " INSERT INTO candidates(first_name, last_name)
VALUES ('$first_name','$last_name')");
Or
mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if you like it better.
The error handling
In order to verify the problem you can echo the mysqli_error() function result whenever the query fails, it's a nice practice and would probably have helped you find a solution faster than asking it here.
$query= mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if(!$query) //the query will return 0 if it fails
{
echo mysqli_error($conn);
}
The security issue
You're adding POST value directly into your query, which is dangerous.
On these lines:
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
You should be escaping user input.
This will escape any special characters that can cause issues in the mysql query.
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);

Categories