Could somebody please point me in the right direction. I am in the process of making the transition from MySql to MySqli. Normally I would select from the database using th code below and it would allow me to easily use the column value as a working variable:
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = mysql_query($SQLCommand);
$DataRow = mysql_fetch_assoc($Data);
$var1 = $DataRow["column1"];
$var2 = $DataRow["column2"];
$var3 = $DataRow["column3"];
$var4 = $DataRow["column4"];
I have researched how to do the MySql equivalent but I find theres a lot of different way using loops etc. Is there a like for like (for want of a better description) that does the same thing? Thanks in advance.
Instead of going with the flow, i care to suggest a PDO alternative
$db = new PDO($dsn, 'username','password');
//$dsn is the connection string to your database.
//See documentation for examples
//The next two rows are optional, but i personally suggest them to
//ease developing, debugging (the 1st) and fetching results (the 2nd)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$stmt = $db->prepare("SELECT * FROM table WHERE column1 = :c1");
$stmt->bindValue(':c1', 'ok'); //This example is trivial and not necessary
//but it gains relevance when the bound value
//is a variable
$rows = $stmt->fetchAll(); //if you expect a single row use fetch() instead
//do something with the results
You can read more about PDO here: PDO manual
The biggest PDO advantage is that it's independent of the actual database in use by your application. If, by chance, you want to change database in the future, for example SQLITE or PostgreSQL, the only* change you have to make is your $dsn connection string
[*] True only if you used standard SQL queries and nothing vendor-specific.
A direct conversion would be:
$Data = mysqli_query($connection, $SQLCommand);
$DataRow = mysqli_fetch_assoc($Data);
The difference, other than the i is that mysqli_query requires the connection as an argument (as do most mysqli_* functions).
MySQLi also has an object oriented style:
$Data = $connection->query($SQLCommand); // assuming you created the $connection object
$DataRow = $data->fetch_assoc();
They should be like
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = $mysqli->query($SQLCommand);
$DataRow = $mysqli->fetch_assoc($Data);
Try this LINK
My suggestion is to use mysqli prepared statement whenever you are using user inputs to prevent SQL injection:
See below code uses object oriented approach and prepared statement
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
!$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
!$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = ?");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
//note below "i" is for integer, "s" can be used for string
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>
Related
I'm using the following snippet:
mysql_connect($host,$user,$password);
$sql = "SELECT FROM ec_opps WHERE id=" . $_GET["UPDATE"];
$item = mysql_query($sql);
mysql_close();
print_r($item);
To try and retrieve data based on the UPDATE value. This value prints to the page accurately, and I know the IDs I'm requesting exist in the database. The print_r($item) function returns no result, not even an empty array, so I'm confused as to where I'm going wrong.
I know it isn't best practise to use MySQL like this, but I'm doing it for a reason.
You're missing columns to be selected in your SELECT query, or you can select all by putting *, which means selecting all column.
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"]."'";
Your query is very prone to SQL injections.
You should refrain from using MySQL. It's deprecated already. You should be at least using MySQLi_* instead.
<?php
/* ESTABLISH CONNECTION */
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT column1, column2 FROM ec_opps WHERE id=?"; /* REPLACE NEEDED COLUMN OR ADD/REMOVE COLUMNS TO BE SELECTED */
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("s", $_GET["UPDATE"]); /* BIND GET VALUE TO THE QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($column1,$column2); /* BIND RESULTS */
while ($stmt->fetch()) { /* FETCH RESULTS */
printf ("%s (%s)\n", $column1, $column2);
}
$stmt->close();
}
$mysqli->close();
?>
Replace with this code
$sql = "SELECT * FROM ec_opps WHERE id=" . $_GET["UPDATE"];
You are missing * in your query.
You need to use:
SELECT * FROM
instead of
SELECT FROM
There is a syntax error in the query. It is missing *. Try with -
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"] . "'";
Please avoid using mysql. Try to use mysqli or PDO. mysql is deprecated now.
I have written a method to get a value out of a database based on an id.
I would like to use the variable id as a parameter in mysql but I can't get it to work.
Here is my code:
function get_color_by_id($id) {
$mysqli = new mysqli("localhost", "root", "usbw", "ipadshop", 3307);
if($mysqli->connect_errno){
die("Connection error: " . $mysqli->connect_error);
}
set #id := $id;
$result = $mysqli->query('SELECT kleur FROM kleur WHERE id=',#id);
if(!$result){
die('Query error: ' . $mysqli->error);
}
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
return $row;
}
}
PHP is not SQL; and SQL code should not be expected to work in a PHP context. The procedural SQLish syntax (set #id := $id) is thus invalid in context, as is the #id expression used later.
As shown here (and updated for this question), the correct way to use parameters in mysqli is with prepare, bind_param, and execute.
$stmt = $mysqli->prepare('SELECT kleur FROM kleur WHERE id = ?');
$stmt->bind_param('i', $id); // assuming $id represents an integer
$result = $stmt->execute();
Since bind_param uses reference calling semantics, the variables used should not be re-assigned once bound to avoid potential confusion.
Also, it can be confusing to give the same names to columns and tables; my preference is to use plural names for tables/relations, and to refine the column names more. Consider a query with different names chosen;
SELECT kleurNaam FROM kleuren WHERE id = ?
-- or in English
SELECT colorName FROM colors WHERE id = ?
Easier to read, no?
I am working in a GUI tool development using php. There are STORED PROCEDURES already present in the database. Those stored procedures cannot be changed. (other tool dependency).
My Question: There is a procedure which returns two tables when called in mysql directly. (maybe 2 select statement inside it).
How can I use 'mysqli -- php' to display the data from two tables returned?
NOTE : Both table returned has same columns(name,id,status) in it
Make use of mysqli::use_result
$mysqli = new mysqli("localhost", "root", "password", "db_name");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
}
$query = "CALL sp_multiple results (?, ?)";
$stmt = $mysqli->prepare($query);
if (!$stmt) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$stmt->bind_param("ss", $param1, $param2);
$stmt->execute();
/* get first result set */
if ($result1 = $mysqli->use_result()) {
//fetch data
$result1->close();
}
/* get second result set */
if ($result2 = $mysqli->use_result()) {
//fetch data
$result2->close();
}
$mysqli->close();
This question already has answers here:
How do I loop through a MySQL query via PDO in PHP?
(3 answers)
Closed 9 years ago.
I am currently using MySQL with PHP but am looking to start MySQLi or PDO
I have while loops like:
$sql="select from ... ";
$rs=mysql_query($sql);
while($result=mysql_fetch_array($rs))
{
$sql2="select from table2 where id = $result["tbl1_id"] ";
}
If I put my MySQLi or PDO queries into a function how can I run things like the above? Doing while loops with queries inside the while loops?
Or is if easier to not do the functions at all and just run the prepared statements as normal?
You wouldn't. And to be honest.. Even in the old days you would not do it this way, but like this:
$sql="select from ... ";
$rs=mysql_query($sql);
$ids = array()
while($result=mysql_fetch_array($rs))
{
$ids[] = $result["tbl1_id"];
}
$sql2="select from table2 where id in ".implode(',', $ids) .";
Or even better, you use a join to run the query just once, on all the tables that need to provide info.
In PDO you can do the same thing. Get all the ID's and the execute a query
I usually take the approach of preparing the query and not using a function. Also I am not clear as to what exactly it is that you want. You want to make your queries as quick and efficient as possible so you should not look to run a while look within another while loop.
This is how my PDO queries usually look
My connection:
$host = "localhost";
$db_name = "assignment";
$username = "root";
$password = "";
try {
$connection = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
MY query:
$query = "SELECT * FROM Table";
$stmt = $connection->prepare( $query );
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
}
It's a duplication question like oGeez say, you have to learn how to code PDO in PHP and other before asking question,
this is the answer:
$dbh = new PDO("mysql:host=" . HOST . ";dbname=" . BASE, USER, PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = 'SELECT * FROM table';
$stmt = $dbh->query($query);
$items = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($items as $item {
print_r($item);
}
the main reason to put it in a function would be if you use the query in multiple files. i have a web app with many queries and i like to keep them in a separate file so that they're easier to track down if i need to make changes. the main thing is that you 1) have to pass your database as a parameter and 2) return the results
function pdoquery($db, $parameter){
$query = "SELECT * FROM table WHERE column=?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $parameter, PDO::PARAM_STR); //or PARAM_INT
if (!$stmt->execute()) {
echo "Could not get results: (" . $stmt->errorCode . ") " . $stmt->errorInfo;
exit;
}
else
$result = $stmt->fetch();
$db = null;
return $result;
}
but as others have mentioned, if its only used once, there's no need for a function, and looping through the results is best done outside of the function as well. however, it is possible to do it inside the function if you want to.
I have the following code and I'm getting crazy with calling an auto_increment id
$sql = "INSERT INTO tablename (x1, x2) VALUES(?,?)";
if($query = $db->prepare($sql)){
$query->bind_param('ss', $x1, $x2);
$query->execute();
$id = mysqli_insert_id($query);
For a reason I don't know why this is not working. I also tried
$id = mysqli_insert_id($sql);
And
$id = mysqli_insert_id();
I just decided to work with mysqli. Before that, I only used MySQL where I had no problem with
$id = mysql_insert_id();
You must pass the mysqli link to mysqli_insert_id(), not the query:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$sql = "INSERT INTO tablename (x1, x2) VALUES(?,?)"
$result = mysqli_query($link, $sql);
$id = mysqli_insert_id($link);
or since you were using object oriented style:
// ...
$id = $mysqli->insert_id;
Probably something like
$query->commit(); OR $query->close();
It's best to stick to OOP style. It will cause you less confusion. In OOP style you only need to access a property on the object. For example:
$stmt = $db->prepare($sql);
$stmt->bind_param('ss', $x1, $x2);
$stmt->execute();
// Either one will work
$stmt->insert_id;
$db->insert_id;
If you want to use the procedural mysqli style then you have to remember that there are two functions. One if for the mysqli object and the other is for mysqli_stmt object. You need to pick either one of them, but you have to pass the right object to it.
// For mysqli_stmt object
mysqli_stmt_insert_id($stmt);
// For mysqli object
mysqli_insert_id($db);
$result = mysql_query($sql);
if(!$result) {
{
die('Error: ' . mysql_error());
} else {
echo "<p>Done!.</p>";
}
Try this and check the output...