I'm currently learning mysqli and systematically replacing all of my deprecated queries throughout my script.
I have this query:
<?php
$link = mysqli_connect("host", "user", "pass", "name");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM pins WHERE id='$pinDetails->id'";
$result = mysqli_query($link, $query);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$feature = $row['featured'];
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
Which I can echo throughout the page as <?php echo $row['date_featured']; ?>
My question is how do I rework the code to remove the connection? I don't want to keep connecting to the db in every query when I have a general connection include at the top of the page.
Actually you need connection for this page to operate based on your SQL database ,, can you explain more that what do you mean by removing connection
you can use INCLUDE();
Related
I try to query the wordpress database from a standalone php file named test.php and located on the root folder of the wp installation folder, but the query return nothing to be displayed, the var dump show nothing, what i do wrong and how to test if the hosting support mysqli?(credentials has been removed from db connection)
enter image description here
<?php
$mysqli = new mysqli('localhost', 'username', 'passwd', 'dbname');
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
$result = $mysqli->query("select meta_value from wpde_postmeta where meta_key = '_product_attributes' and post_id = '41'") ;
echo $result;
var_dump($result);
/* free result set */
$result->close();
$mysqli->close();
?>
You're missing the data fetch part:
// Just below $result = $mysqli->query("...") ;
while($obj = $result->fetch_object()){
// Do something with $obj->meta_value
}
I am stuck with my php code. Parent php page reload again after header() works, Here is my code
<?php
$mysqli = new mysqli("localhost", "root", "root", "testing");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$sql ="update test set hit_count = hit_count+1";
$result = $mysqli->query($sql);
header('Location: http://www.google.com/');
die();
?>
Here some times i got 2 hit_count from db.
How it works, i added die() after header().
You should not output text before using header redirects as seen on the code below:
/* Select queries return a resultset */
if ($result = $mysqli->query($sql)) {
printf("updated");
}else{
echo "failed";
}
Is there a way to test if all connections are properly closed?
<?php
$con = mysqli_connect("localhost", "myuse", "mypass", "myss");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user = $_POST['user'];
$http = $_POST['pass'];
$results = mysqli_query($con, "SELECT * FROM siri");
if (mysqli_num_rows($results) > 0) {
} else {
mysqli_query($con, "INSERT INTO taible(user,http) VALUES('$user', '$http')");
mysqli_query($con, "INSERT INTO mainble(user,http) VALUES('$user', '$http')");
}
mysqli_close($con);
Am I required to close $results?
You have only one connection.
You don't have to check if it closed.
You aren't required to close $results either.
What should be your real concern instead is use of prepared statements.
You can check if a connection is open with mysqli_ping()
Example:
if(mysqli_ping($con)){
//do stuff if it is open
}
http://www.php.net/manual/en/mysqli.ping.php
And so just do that for each connection you have to check if any are open.
However, most people agree, you don't need to close the connection. It is automatically dumped when the script ends, and you are more likely to have errors and add stress to the db by opening and closing connections.
I try to echo my database (hosted on ipage.com) using php and I get this error : Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, cgiadmin#yourhostingaccount.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
What is wrong? $mysqli = new mysqli("site.ipagemysql.com", "user", "pass", "database");
alone, works, so it is not a error in the connection right? or I have to contact the host?
My code
<?php
$mysqli = new mysqli("site.ipagemysql.com", "user", "pass", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf("Host information: %s\n", $mysqli->host_info);
$result = mysqli_query($link, "SELECT DATABASE()"))
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);
mysqli_free_result($result);
?>
You have one ) too many on line 12, it's missing a semicolon and you haven't changed the $link variable to correspond with the $mysqli variable on line 3.
$result = mysqli_query($mysqli, "SELECT DATABASE()");
Also, you're mixing object oriented style with procedural style. I'd recommend you to use OO style only. So the code would be:
<?php
$mysqli = new mysqli("site.ipagemysql.com", "user", "pass", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf("Host information: %s\n", $mysqli->host_info);
$result = mysqli->query("SELECT DATABASE()"))
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
$mysqli->close();
?>
I have a JSON string with me
{"name":"jack","school":"colorado state","city":"NJ","id":null}
I need it to be saved in the Database. How could i do this ?
My PHP code (I have only establish the connection to MySQL, but i am unable to save the records)
<?php
// the MySQL Connection
mysql_connect("localhost", "username", "pwd") or die(mysql_error());
mysql_select_db("studentdatabase") or die(mysql_error());
// Insert statement
mysql_query("INSERT INTO student
(name, school,city) VALUES(------------------------- ) ") // (How to write this)
or die(mysql_error());
echo "Data Inserted or failed";
?>
We'll use json_decode json_decode documentation
Also be sure to escape! here's how I would do it below...
/* create a connection */
$mysqli = new mysqli("localhost", "root", null, "yourDatabase");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* let's say we're grabbing this from an HTTP GET or HTTP POST variable called jsonGiven... */
$jsonString = $_REQUEST['jsonGiven'];
/* but for the sake of an example let's just set the string here */
$jsonString = '{"name":"jack","school":"colorado state","city":"NJ","id":null}
';
/* use json_decode to create an array from json */
$jsonArray = json_decode($jsonString, true);
/* create a prepared statement */
if ($stmt = $mysqli->prepare('INSERT INTO test131 (name, school, city, id) VALUES (?,?,?,?)')) {
/* bind parameters for markers */
$stmt->bind_param("ssss", $jsonArray['name'], $jsonArray['school'], $jsonArray['city'], $jsonArray['id']);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
Hope this helps!
This is example for help you
<?php
$json = '{"name":"jack","school":"colorado state","city":"NJ","id":null}';// You can get it from database,or Request parameter like $_GET,$_POST or $_REQUEST or something :p
$json_array = json_decode($json);
echo $json_array["name"];
echo $json_array["school"];
echo $json_array["city"];
echo $json_array["id"];
?>
Hope this help !
Decode into an array and pass it in your mysql_query, the code below is not using mysql_real_escape_string or any other means of security, which you should implement.
Assume $json is {"name":"jack","school":"colorado state","city":"NJ","id":null}
$json_array = json_decode($json);
You now have indexes in a php array, such as: $json_array['name']
mysql_query("INSERT INTO student (name, school,city) VALUES('".$json_array['name']."', '".$json_array['school']."', '".$json_array['city']."') ") or die(mysql_error());