Can I run a sql query in another file? - php

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 :)

Related

Simple php - mysql select and insert

I am not a programmer (duh), I just need to make a really simple tool for populating sql database. First I have html with form:
<form action="http://localhost:8081/phpSearch.php" method ="post">
Enter code: <input type="text" name="search"><br>
<input type ="submit">
</form>
and then php that should connect to MYSQL, search for data according to input (code,name) in one table and then populate another table with the result. And I'm only mising what to put instead of question marks.
<?php
$search1 = $_POST['search'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT code,name FROM users WHERE code LIKE '%$search1%'";
$sql2 = "INSERT INTO newUsers (newCode,newName) VALUES ('$search1', ??????)";
$conn->close();
?>
I'm pretty sure this is easy for you experts, so thanks in advance.
You could actually do this in a single SQL query:
$search1 = "%".$_POST['search']."%";
$sql = "INSERT INTO newUsers (newCode, newName) SELECT code, name FROM users WHERE code LIKE ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $search1);
$stmt->execute();
This will insert all the results of the SELECT query directly into the other table, without needing any intermediate processing in PHP. More about the INSERT...SELECT query format can be found here.
Note I've used prepared statements and parameters - which both executes the query securely and reduces the risk of accidental syntax errors. You can get more examples of this here.
Also, in a real application you shouldn't log in as root from your web application - instead create a SQL account for the application which has only the privileges it actually needs.

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']);

Non object error when using prepared statement

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=?");

migrating mysql to mysqli in ajax environment

First i would like to say thank you for letting me ask questions again. I know my previous question was a bit low level of knowledge. Today, I would like to ask if the principle of converting mysql to mysqli in ajax is same with html. Suppose this is my Connect.php
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "765632";
$dbname = "student";
$link_id = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link_id));
?>
and my ajax.php is
<?php
//Connect to MySQL Server
include 'Connect.php';
mysql_connect($host, $dbusername, $dbpassword);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Escape User Input to help prevent SQL Injection
$first_name = mysql_real_escape_string(trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysql_query($query) or die(mysql_error());
//Generate the output
$searchResults = '';
if(!mysql_num_rows($result))
What are the changes should i made to convert it to mysqli without changing its logical scheme.
Did you mean this?
$link_id = mysqli_connect($host, $dbusername, $dbpassword);
//Select Database
mysqli_select_db($link_id, $dbname) or die(mysqli_error($link_id));
// Escape User Input to help prevent SQL Injection
$first_name = mysqli_real_escape_string($link_id, trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysqli_query($link_id, $query) or die(mysqli_error($link_id));
//Generate the output
$searchResults = '';
if(!mysqli_num_rows($result))

Categories