select an attribute in mysql, php - php

I just start to learn about phpMyAdmin and mysql. here's a question: I want to select something in my "student" table and it echo the result. but as I checked it returns 0 row for the search. but I have it in my database.
here is my code:
$conn = new mysqli($servername, $username, $password, $dbname);
$params="#name varchar(30)";
$paramslist="#name='$name%";
$sql = "SELECT name,address,city,birthday FROM student WHERE NAME=#NAME";
$dbsql = "EXEC sp_executesql
N'$sql',
N'$params',
$paramslist";
$result = $conn->query($sql);
ECHO $result->num_rows;
I don't know what is the problem. thank you for helping.

$sql = "SELECT name,address,city,birthday FROM student WHERE name=".$name;
$result = $conn->query($sql);
echo $result->num_rows();

this is what works for me with prepared statement
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name='Veshraj Joshi';
$stmt = $conn->prepare("SELECT name,address,city,birthday FROM student WHERE NAME=?");
/* bind parameters for markers */
$stmt->bind_param("s", $name);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
/* now you can fetch the results into an array */
while ($student = $result->fetch_assoc()) {
// use your $student array as you would with any other fetch
echo $student['address'].'<br>';
}

The following uses prepared statements. You should always use prepared statements when including user input to safeguard for SQL Injection attacks.
Every time fetch() executes, the results are bound to the variables specified by bind_result()
$conn = new mysqli($servername, $username, $password, $dbname);
$query = "SELECT name,address,city,birthday FROM student WHERE name=?";
$stmt = $conn->prepare($query);
$searchTerm = "%$name%";
$stmt->bind_param('s', $searchTerm);
$stmt->execute();
$stmt->bind_result($resultName, $resultAddress, $resultCity, $resultBirthday);
while($stmt->fetch())
{
echo $resultName . " " . $resultAddress . " " . $resultCity . "<br/>";
}

Related

Problems with my first prepared MySQLi

Following a question earlier about sanitising a string, I'm now attempting to use the principles seen at How can I prevent SQL injection in PHP?
$connection = mysqli_connect('localhost', 'user', 'xxxxx');
$database = mysqli_select_db($connection, 'xxxxx');
$param1 = $_GET['q'];
//prepared mysqli statement
$stmt = mysqli_stmt_init($connection);
$stmt = $connection->prepare('SELECT * FROM CONTACTS WHERE SURNAME = ?');
$stmt->bind_param('s', $param1); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
$num_rows = mysqli_num_rows($result);
echo "Records Found:".$num_rows."<br/><br/><hr/>";
while ($row = $result->fetch_assoc()) {
echo $result['COMPANY']." ".$result['FORENAME']." ".$result['SURNAME'];
}
However, although $connection and $database are both processing correctly, I'm getting the following error:
Fatal error: Call to undefined method mysqli_stmt::get_result() in
/my_first_mysqli.php on line xxxx
Am I not getting the syntax correct or does it have more to do with the php version 5.2.0 I'm rocking. (Yes, I'm upgrading code before upgrading server).
If it's the latter, is there a simpler MySQLi method I can use that will work before I upgrade the php version?
EDIT
I've updated this now which is a bit cleaner:
$servername = "localhost"; $username = "xxxx"; $password = "xxxx"; $dbname = "xxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$param1 = $_GET['q'];
$stmt = mysqli_prepare($conn, "SELECT CONTACTID, COMPANY, FORENAME, SURNAME FROM CONTACTS WHERE SURNAME = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $param1);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $CONTACTID, $COMPANY, $FORENAME, $SURNAME);
/* fetch value */
mysqli_stmt_fetch($stmt);
$num_rows = mysqli_num_rows($stmt);
echo "Records Found:".$num_rows."<br/><br/><hr/>";
/* close statement */
mysqli_stmt_close($stmt);
mysqli_close ($conn);
I'm obviously not getting a recordset result to loop through and don't know how to... The rest appears to work without throwing an error.
Thanks for all the contributions. I now have a working procedural solution that I thought I'd post for reference.
It's a bit cumbersome but it's fine and I believe it follows good modern practice.
$servername = "localhost"; $username = "xxxx"; $password = "xxxx"; $dbname = "xxxx";
$conn = new mysqli($servername, $username, $password, $dbname);// Create connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$param1 = $_GET['q'];
$stmt = mysqli_prepare($conn, "SELECT CONTACTID, COMPANY, FORENAME, SURNAME FROM CONTACTS WHERE SURNAME = ?");
mysqli_stmt_bind_param($stmt, "s", $param1);// bind parameters for markers
mysqli_stmt_execute($stmt);// execute query
mysqli_stmt_bind_result($stmt, $CONTACTID, $COMPANY, $FORENAME, $SURNAME);// bind result variables
// fetch values
while (mysqli_stmt_fetch($stmt)) {
echo $CONTACTID."<br>";
echo $COMPANY."<br>";
echo $FORENAME."<br>";
echo $SURNAME."<br>";
echo "<hr/>";
}
mysqli_stmt_close($stmt);// close statement
mysqli_close ($conn);
Feedback welcome if you can see any improvements.

Mysql get count with php prepared

I want get count rows in my table. How can I do it?
<?php
require_once "config.php";
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT COUNT(*) FROM `books`");
$stmt->execute();
$result = $stmt->get_result();
?>
Try this :
$query = "SELECT COUNT(*) FROM books";
$stmt = $conn->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($Count);
$stmt->fetch();
echo "Count: $Count";

How to get count using prepared statment in PHP?

$con = mysqli_connect("localhost","root","","uploads");
if($con)
{
$sql = "SELECT COUNT(id) FROM products";
$obj = mysqli_query($con,$sql);
if(is_object($obj))
{
$rows = mysqli_fetch_row($obj);
$totalrows = $rows[0];
enter code here
}else{
echo "not object";
}
}else
{
echo "db issue";
}
This code is perfectly fine but i want to perform same operation using prepared statment.i have tried but could't get the same result using prepared statment. what i have to do?
Check out the following solutions
//db configuration
$server = 'localhost';
$dataBase = 'uploads';
$UserName = 'root';
$Password = '';
PHP MySQLi Prepared Statement
$con = mysqli_connect($server, $userName, $password, $dataBase);
$sql = "SELECT COUNT(id) FROM products";
$stmt = mysqli_prepare($con, $sql);
if(mysqli_stmt_execute($stmt)) {
mysqli_stmt_bind_result($stmt, $totalRows);
mysqli_stmt_fetch($stmt);
echo $totalRows;
}
PHP MySQLi Object-oriented
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->query("SELECT COUNT(id) FROM products");
if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_row()) {
$totalRows = $row[0];
echo 'Total number of rows is '.$totalRows;
}
}
$stmt->close();
PHP MySQLi with Object-oriented Prepared Statement
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
echo 'Total number of rows is '.$totalRows;
$stmt->close();
PHP PDO with Prepared Statement
try {
$con = new PDO("mysql:host=$server;dbname=$dataBase;", $userName, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$totalRows = $stmt->fetchColumn();
echo 'Total number of rows is '.$totalRows;
} catch(PDOException $e){
echo $e->getMessage();
die();
}

How to fetch assoc array while using mysqli prepare

To make sure my database is secure I'm using prepare statements. Here is my code:
//connecting to MySql database
$con=mysqli_connect("host","user","pass","dbname");
// checking database connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_prepare($con,"SELECT * FROM `table` WHERE emb=? LIMIT 1");
mysqli_stmt_bind_param($stmt, 's', $emb);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
Now I want to know how can I use ASSOC fetch array
$embInfo = mysqli_fetch_array($stmt, MYSQLI_ASSOC);
I want this so that I can just put something like below to get values
$embInfo['name']
and
$embInfo['email']
try this:
//connecting to MySql database
$con=mysqli_connect("host","user","pass","dbname");
// checking database connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_prepare($con,"SELECT * FROM `table` WHERE emb=? LIMIT 1");
mysqli_stmt_bind_param($stmt, 's', $emb);
mysqli_stmt_execute($stmt);
while($embInfo = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
echo 'My name is '.$embInfo['name'].'and my email is '.$embInfo['email'].'<br/>';
}
mysqli_stmt_close($stmt);
May i suggest an alternative
{
$server = '';
$user = '';
$pass = '';
$db = '';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
$club=$_POST'club'];
$sql = "SELECT * FROM players WHERE club = '$club'";
$result=mysqli_query($mysqli,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['player'];
}
}

Issue inserting data using mysqli in MySQL

I try to use mysqli in order to insert data in my database. But does not work. Where may be the error?
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statment = $myDb->prepare("INSERT INTO user(name,surname,age)
VALUES (?,?,?)");
$statement->bind_param('s', $_POST['name']);
$statement->bind_param('s', $_POST['surname']);
$statement->bind_param('i', 25);
$statement->execute();
$statement->free_result();
EDIT:
I obtain this error:
Binding parameters failed: (0) Execute failed: (2031) No data supplied for parameters in prepared statement
You've got the error here:
$statement->bind_param('i', 25);
25 is not a variable. You can only use variables when binding parameters. You can't use constants nor fixed strings or numbers when binding.
Besides, it never worked for me to split the parameters when binding. I got an error. I need to do so:
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statement = $myDb->prepare("INSERT INTO user (name,surname,age) VALUES (?,?,25)");
$statement->bind_param('ss', $_POST['name'], $_POST['surname']);
$statement->execute();
$statement->free_result();
$statement->close();
I solved the problem using a correct bind of parameter. Here the correct code:
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statment = $myDb->prepare("INSERT INTO user(name,surname,age)
VALUES (?,?,?)");
$statement->bind_param('s', $name);
$statement->bind_param('s', $surname);
$statement->bind_param('i', $age);
$name = $_POST['name'];
$surname = $_POST['surname'];
$age = 25;
$statement->execute();
$statement->free_result();

Categories