PHP - Execute SQL calling function does not work [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I'm new to PHP, I have no clue what I'm doing. I'm trying to perform an insert into my MSSQL database. Not really sure why this is not working.
function Register_WBG_Tester($Email, $FullName, $ChatHandle, $Product, $PreferedGenre, $PreviousTester, $AgeGroup, $PlayTime, $Discord, $NDA)
{
sqlsrv_configure('WarningsReturnAsErrors',0);
$query;
$result;
$query = (string)"
DECLARE #Response AS BIT = 0;
IF NOT EXISTS(SELECT Email FROM [dbo].[WBG_Tester] WHERE [Email] = $Email) BEGIN
INSERT INTO [dbo].[WBG_Tester]
([Email]
,[Full_Name]
,[Chat_Handle]
,[Product]
,[Prefered_Genre]
,[Previous_Tester]
,[Age_Group]
,[Play_Time]
,[Discord]
,[NDA_Agreement])
VALUES
($Email
,$FullName
,$ChatHandle
,$Product
,$PreferedGenre
,$PreviousTester
,$AgeGroup
,$PlayTime
,$Discord
,$NDA
)
SET #Response = 1
END ELSE BEGIN
SET #Response = 0
END
SELECT #Response"
$result =(bool)mssql_query($query);
return $result;
}
I've never worked with PHP before, mostly work with .Net I would prefer to exec calling a stored proc rather then string query. Any help would be great. Everything I've found was for MySQL. seems to be preferred for PHP.

This is how you can execute store procedures in php
sqlsrv_prepare ( resource $conn , string $sql [, array $params [, array $options ]] ) : mixed
Prepares a query for execution. This function is ideal for preparing a query that will be executed multiple times with different parameter values.
$sql = "EXEC stp_Create_Item #Item_ID = ?, #Item_Name = ?";
$stmt = sqlsrv_prepare($conn, $sql, $procedure_params);
if (!sqlsrv_execute($stmt)) {
echo "Your code is fail!";
die;
}
while($row = sqlsrv_fetch_array($stmt)){
//Stuff
}
For more details please visit, php official documentation.

Related

PHP not showing MySQL results with variable in query [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I have been using the same code for years and all of a sudden I'm having problems that I cannot figure out. I am making a very simple query to MySQL in PHP using a variable in the statement. When I use the variable, it returns no results. When I manually type in the value of the variable instead, it works. I use this syntax all day long and never have had a problem. What on earth is wrong?
$name = "Fred";
$query = "SELECT * FROM database WHERE name='".$name."'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) != 0) {
echo "Found record.";
}
If I replace the $name variable with Fred, it finds the record. If I echo the query with the variable before it executes and place that exact statement into MySQL directly in phpMyAdmin, I also get the result. If I leave the statement as-is with the variable in place, I get no result. Please help.
your query states SELECT * FROM database WHERE name='".$name."', this means that your table name is database, now i dont know how you actually created this table but database is a MYSQL reserved keyword change the name of your table to something else or just change your query to
$query = "SELECT * FROM `database` WHERE name='$name'";
assuming that your database connection is fine your code should now work
also worth noting, whenever acquiring data from a database use prepared statements instead of raw data as it makes you vulnerable to sql injection, in your case your code should be something like this
$name = "Fred";
$stmt = $dbconnection->prepare("SELECT * FROM table_name WHERE name=?")
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows != 0)
{
echo "Found record.";
}
this is more secure
You shouldn't use mysqli excepted for old projects you can't upgrade, it's outdated and suffers from potential sql injection vulnerabilities.
Instead, I recommand you to learn PDO and prepared statements.
Your request should look like this :
$name = 'Fred';
$sql = "SELECT * FROM my_user_table WHERE name = :name";
// You should have set your pdo instance in a script handling your database connexion and reusing it in any script making requests.
$result = $pdo->prepare($sql);
// Here you dynamically inject values in your request and tells pdo what type of data you are expecting
$result->bindValue(':name', $name, PDO::PARAM_STR);
$result->execute();
if( $result->rowCount()) {
echo "{$result->rowCount()} result(s) found";
}
else {
echo 'No result found';
}
Here's the official doc :
https://www.php.net/manual/fr/book.pdo.php
This will also more than probably fix your problem.

How to delete a row in a database with pdo ($stmt stated false) [duplicate]

This question already has answers here:
delete using where and or
(4 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 4 years ago.
I'm coding a blog to get experience with php.
I want the admin to be able to delete a post, but when I click the delete-button which should actually bring me to a function that deletes the post I get the error Call to a member function execute() on boolean.
Here is the code of the postsRepository.php which interacts with the database and the function in the postsAdminController.php:
public function deletePost($id)
{
$table = $this->getTableName();
$model = $this->getModelName();
$stmt = $this->pdo->prepare("DELETE * FROM `{$table}` WHERE id = :id");
$stmt->execute([
'id' => $id
]);
}
public function deletePost()
{
$id = $_GET['id'];
if ($this->postsRepository->deletePost($id)) {
header("Location: posts-admin");
return;
} else {
}
}
I've var_dumped the $id right before the $stmt, it's correct and the shown error says the it is because of $stmt->execute([.
The $stmt is stated as false when I var_dumped it, but why?
The correct syntax for DELETE is
DELETE FROM tableName WHERE ...
Remove the * in your query.
$stmt is false because "If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling)."
For more informations, check the documentation

PHP bind_param not binding parameter [duplicate]

This question already has answers here:
MySQLI Prepared Statement: num_rows & fetch_assoc
(5 answers)
Closed 5 years ago.
I am trying to search a table for specific items using a prepared statement in PHP. I am getting no errors, but also getting no record. Here is my code:
$items = [];
$search = "john";
if ($stmt = $this->con->prepare("SELECT * FROM phptest WHERE search = ?")) { //'john'";
$stmt->bind_param("s",$search);
$stmt->execute();
while ($row = mysqli_fetch_array($stmt)) {
$item = [];
$item['id'] = $row['id'];
$item['first'] = $row['search'];
$item['last'] = $row['data'];
array_push($items, $item);
}
}
return $items;
Now, when I don't use a prepared statement, and just SELECT * FROM phptest I get all the results in the table (including the item where search = 'john'). Furthermore, if I use the query SELECT * FROM phptest WHERE search = 'john' I get the one record where search = 'john'
But as soon as I turn it into the prepared statement, I get zero errors but zero records. I do get a warning:
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
Which made me think my bind_param or execute() was returning FALSE, but when I check, it does not appear to be returning false.
I started off my adventure working through the tutorial https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/, which I thought I understood fully but ran into my error when trying to make my own PHP API.
I then went to the manual http://php.net/manual/fr/mysqli.prepare.php, but still cannot find my error.
Though it has been closed as "off-topic," I have reviewed PHP bind_param not working and found nothing applicable to my situation.
Likewise, I am not finding the error in PHP bind_param not defined nor php bind_param is not working.
You're very close. mysqli_fetch_array() expects to be passed a result object, not the statement object itself:
$stmt = $conn->prepare(...);
$stmt->bind_param(...);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_array($result)) {
Or, in the fully OO manner:
while ($row = $result->fetch_array()) {

PHP PDO execute/prepare doesn't seem to work [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
<?php
$abc = $objpdo->prepare("SELECT * FROM testdb.users WHERE user = ':login' AND user_pass=PASSWORD(':password')");
$abc->bindParam(':login', $_POST['name']);
$abc->bindParam(':password', $_POST['pw']);
$abc->execute();
echo $abc->rowCount();
// the example above doesn't work rowCount is always 0
$abc = $objpdo->prepare("SELECT * FROM testdb.users WHERE user = '?' AND user_pass=PASSWORD('?')");
$abc->execute([$_POST['name'], $_POST['pw']]);
echo $abc->rowCount();
// and again rowCount is always 0
$abc = $objpdo->query("SELECT * FROM testdb.users WHERE user = '".$_POST['name']."' AND user_pass=PASSWORD('".$_POST['pw']."')");
echo $abc->rowCount();
// this thing here is working
?>
The prepared statements i have at my code doesn't seem to work,
the strange thing is when i try running query() without preparing it but just directly passing the values to the string its working.
Note that i always try this code with existed users/passwords.
The placeholders don't need quotes around them or else the query will just treat them as strings, not placeholders.
$abc = $objpdo->prepare("SELECT * FROM testdb.users WHERE user = :login AND user_pass=PASSWORD(:password)");
Same with the ordinal placeholders (question marks):
$abc = $objpdo->prepare("SELECT * FROM testdb.users WHERE user = ? AND user_pass=PASSWORD(?)");

Object can't be converted to a string in MySQLi PHP [duplicate]

This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\xxx\dash.php on line 20
I am quite fairly new, and being a old-school coder, simply using mysql_result to grab such data, I am unaware of how to go about this. I have a class->function setup.
Line 20 of dash.php contains:
echo $user->GetVar('rank', 'Liam', $mysqli);
While, the function is:
function GetVar($var, $username, $mysqli)
{
$result = $mysqli->query("SELECT " . $var . " FROM users WHERE username = '" . $username . "' LIMIT 1");
return $result;
$result->close();
}
Now, to my understanding, I am meant to convert $result into a string, but I am not fully aware of how to do so. I've tried using a few methods, but to no avail. So I've come to the community to hopefully get a answer, I've also looked around but noticed that all other threads are asking for num_rows, while I just want to grab the string from the query select.
You have to fetch it first before echoing the results. Rough Example:
function GetVar($var, $username, $mysqli) {
// make the query
$query = $mysqli->query("SELECT ".$var." FROM users WHERE username = '".$username."' LIMIT 1");
$result = $query->fetch_assoc(); // fetch it first
return $result[$var];
}
Then use your function:
echo $user->GetVar('rank', 'Liam', $mysqli);
Important Note: Since you're starting out, kindly check about prepared statements. Don't directly append user input on your query.
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()) {
echo row['column_name'];
}
}
$result->close();
where you see 'column_name put the name of the column you want to get the string from.

Categories