Creating Json file from mysql - mysql

i can't get more than one return in this json. when the original query returns 90k results.
i can't figure out what's hapening.
also the return i get isn't organized as it should. it return the following
{"material":["R8190300000","0"],"grid":["R8190300000","0"]}
sorry to ask this i have been looking for an answer but couln't get it in the internet.
<?php
$link = mysqli_connect("localhost","blablabla","blablabla","blablabla");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query =" SELECT material,grid FROM ZATPN";
if( $result = mysqli_query( $link, $query)){
while ($row = mysqli_fetch_row($result)) {
$resultado['material']=$row;
$resultado['grid']=$row;
}
} else {
echo"doesnt work";
}
file_put_contents("data.json", json_encode($resultado));
?>

The problem is that you are overriding the value for the array keys:
$resultado['material']=$row;
$resultado['grid']=$row;
At the end you will have only the last 2 rows; I suggest you to use something like:
$resultado['material'][] = $row;
$resultado['grid'][] = $row;
This will save you pair rows in $resultado['grid'] and unpaired rows in $resultado['material'];
After the information in comments you can use this code:
$allResults = array();
while ($object = mysqli_fetch_object($result)) {
$resultado['id'] = $object->id;
$resultado['name'] = $object->name;
$resultado['item'] = $object->item;
$resultado['price'] = $object->price;
$allResults[] = $resultado;
}
file_put_contents("data.json", json_encode($allResults));

Related

WordPress and PHP | Check if row exists in database if yes don't insert data

I'm fairly new to WordPress and SQL. I have a contact form that I want to have the data be submitted to my WordPress database but only if the data that has been entered has not been entered before.
This is what i have so far, which sends data to my database when form is submitted.
if(isset($_POST['contact_us'])) {
$invalidContact = "<h5 class='invalidBooking'> Nope try again</h5>";
$successContact = "<h5 class='invalidBooking'> Message Sent!</h5>";
$table_name='contact_table';
global $wpdb;
$contact_name = esc_attr($_POST['contact_name']);
$contact_email = sanitize_email($_POST['contact_email']);
$subject = esc_attr($_POST['subject']);
$message = esc_attr($_POST['message']);
$error= array();
if (empty($contact_name)) {
$error['name_invalid']= "Name required";
}
if (empty($contact_email)){
$error['email_invaild']= "Email required";
}
// Im guessing some code here to check if row exists in database
if (count($error) >= 1) {
echo $invalid;
}
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
echo $successContact;
}
}
You may try this code
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$query = "SELECT * FROM $table_name WHERE 'Contact_Name'= '$contact_name' AND 'Contact_Email' = '$contact_email' AND 'Contact_Subject' = '$subject' AND 'Contact_Message' = '$message'";
$query_results = $wpdb->get_results($query);
if(count($query_results) == 0) {
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
}
}
Hope this works for you.
fetch data using this code
$query = "SELECT * FROM {$wpdb->prefix}table WHERE column = 1";
echo $query;
$results = $wpdb->get_results($query);
and then you know what to do...

SQL can't found any values

i'm having trouble returning values of sql rows, my SQL request work well on console but can't return a row of it with my code, any help ? thanks !
<?php
require_once 'sql.php';
$sqlConnexion = new mysqli($hn,$un,$pw,$db);
if($sqlConnexion->connect_error){
die ('Soucis de connexion SQL');}
$date = date("d/m/y G:i:s");
if(isset($_POST['zoneDeText'])){
$area = $_POST['zoneDeText'];
$queryone= "SELECT SortieTraitée FROM entry WHERE entréesUtilisateurs=?";
$instruction = $sqlConnexion->prepare($queryone);
if(!$instruction->prepare($queryone)){
echo "$instruction->errno";
}else{
$instruction->bind_param('s', $area);
$instruction->execute();
$result = $instruction->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)){
foreach ($row as $out){
if($out == $area){
echo $out;
}elseif($out != $area){
echo 'Still not found';
}
}
}
$instruction->close();
}
?>
You don't actually print anything, you just return the value, which makes no sense unless your code is inside a function.
if($out == $area){
return $out;
}
The documentation http://php.net/return says:
If return is called from within the main script file, then script execution ends.
Unless the code you show above has been included in another PHP script, that means it will just end the script and output nothing.
There are several other confusing things your script, but the above is probably the one directly responsible for the problem you're asking about.
Here's how I might write this code:
if (isset($_POST['zoneDeText'])) {
$area = $_POST['zoneDeText'];
$queryone = "SELECT SortieTraitée FROM entry WHERE entréesUtilisateurs=?";
$instruction = $sqlConnexion->prepare($queryone);
// if the prepare fails, it is false
if ($instruction === false) {
// false is not an object, it has no error attribute
// the error is an attribute of the connection
die($sqlConnexion->error);
}
$instruction->bind_param('s', $area);
$instruction->execute();
$result = $instruction->get_result();
// if there are zero rows in the result, the while loop
// will finish before it starts, so there will be no output
// so first check for a result of zero rows in the result
if ($result->num_rows == 0) {
echo("Found zero rows");
} else {
while ($row = $result->fetch_assoc()) {
echo $row["SortieTraitée"];
}
}
$instruction->close();
}

Get data into array using mysql prepared statements

I'm trying to get the function below to return an array of user_ids. Here is the function in php.
function users_following($follower_id)
{
include "dbconn.php";
$stmt = mysqli_prepare($con, "SELECT user_id FROM follo WHERE follower_id = ?");
mysqli_stmt_bind_param($stmt, "i", $follower_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $following_user_id);
$count = 0;
$user_array = array();
while (mysqli_stmt_fetch($stmt) ) {
$user_array[] = $following_user_id;
$count = $count + 1;
}
mysqli_stmt_close($stmt);
if ($count > 0)
{
return $user_array;
} else {
return false;
}
}
The problem is that the above function just returns the output: 'Array' (without quotes), when I tested with the code below, not the list of user_ids.
$userid_array = users_following($_SESSION["user_id"]);
echo $userid_array;
Can anyone please help me out? If you need additional details, just comment below and I will try to clarify.

How to fetch row from custom table in drupal 7?

I have used
$member_id = 12;
$results = db_query("select * from {customorders} where id = :fid", array(':fid' => $member_id));
foreach($results as $result) {
$name = $result['name'];
}
but I get error Fatal error: Cannot use object of type stdClass as array
so what could be solution , and please correct me if I have written wrong query for select
i want "select * from customorders where id = 12"
and customorders is my created custom table in Drupal database
Please help me..
Thanks
The $result variable is returned as an array of objects. So you should use $result->name instead of $result['name'].
Your code can be fixed to be like that:
$member_id = 12;
$results = db_query("select * from {customorders} where id = :fid", array(':fid' => $member_id));
foreach($results as $result) {
$name = $result->name; // THE EDITED LINE.
}
Hope this works... Muhammad.
This worked for me:
$member_id = 12;
$results = db_query("select * from {customorders} where id = :fid", array(':fid' => $member_id))->fetchAll();
foreach($results as $result) {
$name = $result->name; // THE EDITED LINE.
}
Note the fetchAll() which resulted in the actual data, without this I got the database object only.

Was: Grab the last inserted id - mysql Now: Where should we call the last insert id?

Here's the thing, I don't have access to code that inserts data into a given table. However, I need to add related additional data into another table. So, I was thinking about grabbing the last inserted ID and from there... insert the related data into that other table.
Since I don't have access to the statement, I believe that mysql last insert id function will be of no use here.
All the PDO::lastInsertId examples that I see, are also attached to some "insert query" before it, so no use as well.
How can I grab the last inserted ID on the cases were we DON'T have access to the original insert statement ?
Data flow:
It starts here: signup.tpl
Where we have:
onclick="checkoutvalidate();return false"
On the js we have:
function checkoutvalidate() {
$.post("order/index.php", 'a=validatecheckout&'+$("#orderfrm").serialize(),
function(data){
if (data) {
...
} else {
document.orderfrm.submit();
}
});
So, now, let's look for "validatecheckout" into index.php
And we found it:
We can't read along this lines, anything concerning the insertion. The immediately after that I can get is, after the conditional statement - right ?
if ($a=="validatecheckout") {
$errormessage = '';
$productinfo = getProductInfo($pid);
if ($productinfo['type']=='server') {
if (!$hostname) $errormessage .= "<li>".$_LANG['ordererrorservernohostname'];
else {
$result = select_query("tblhosting","COUNT(*)",array("domain"=>$hostname.'.'.$domain,"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Cancelled"),"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Terminated"),"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Fraud")));
$data = mysql_fetch_array($result);
$existingcount = $data[0];
if ($existingcount) $errormessage .= "<li>".$_LANG['ordererrorserverhostnameinuse'];
}
if ((!$ns1prefix)OR(!$ns2prefix)) $errormessage .= "<li>".$_LANG['ordererrorservernonameservers'];
if (!$rootpw) $errormessage .= "<li>".$_LANG['ordererrorservernorootpw'];
}
if (is_array($configoption)) {
foreach ($configoption AS $opid=>$opid2) {
$result = select_query("tblproductconfigoptions","",array("id"=>$opid));
$data = mysql_fetch_array($result);
$optionname = $data["optionname"];
$optiontype = $data["optiontype"];
$qtyminimum = $data["qtyminimum"];
$qtymaximum = $data["qtymaximum"];
if ($optiontype==4) {
$opid2 = (int)$opid2;
if ($opid2<0) $opid2=0;
if ((($qtyminimum)OR($qtymaximum))AND(($opid2<$qtyminimum)OR($opid2>$qtymaximum))) {
$errormessage .= "<li>".sprintf($_LANG['configoptionqtyminmax'],$optionname,$qtyminimum,$qtymaximum);
$opid2=0;
}
}
}
}
$errormessage .= checkCustomFields($customfield);
if (!$_SESSION['uid']) {
if ($_REQUEST['signuptype']=="new") {
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$companyname = $_REQUEST['companyname'];
$email = $_REQUEST['email'];
$address1 = $_REQUEST['address1'];
$address2 = $_REQUEST['address2'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$postcode = $_REQUEST['postcode'];
$country = $_REQUEST['country'];
$phonenumber = $_REQUEST['phonenumber'];
$password1 = $_REQUEST['password1'];
$password2 = $_REQUEST['password2'];
$temperrormsg = $errormessage;
$errormessage = $temperrormsg.checkDetailsareValid($firstname,$lastname,$email,$address1,$city,$state,$postcode,$phonenumber,$password1,$password2);
$errormessage .= checkPasswordStrength($password1);
} else {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (!validateClientLogin($username,$password)) $errormessage .= "<li>".$_LANG['loginincorrect'];
}
}
if (($CONFIG['EnableTOSAccept'])AND(!$_REQUEST['accepttos'])) $errormessage .= "<li>".$_LANG['ordererrortermsofservice'];
$_SESSION['cart']['paymentmethod'] = $_REQUEST['paymentmethod'];
if ($errormessage) echo $_LANG['ordererrorsoccurred']."<br /><ul>".$errormessage."</ul>";
else {
if ($_REQUEST['signuptype']=="new") {
$userid = addClient($firstname,$lastname,$companyname,$email,$address1,$address2,$city,$state,$postcode,$country,$phonenumber,$password1);
}
}
//DO THE DO INSERT_LAST_ID() here ?
}
Thanks in advance,
MEM
After the insert statement you can fire another query:
SELECT LAST_INSERT_ID();
and this will return one row with one column containing the id.
Docs: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
mysql> SELECT LAST_INSERT_ID();
-> 195
This works per connection so there is no problem if another thread writes into the table. But your SELECT needs to be executed 'RIGHT AFTER'/'As the next query' after the insert query ran
Edit
An example:
$dbConnection = MyMagic::getMeTheDatabase("please");
$oSomeFunkyCode->createThatOneRowInTheDatabase($dbConnection);
$result = $dbConnection->query("SELECT LAST_INSERT_ID();");
// ... fetch that one value and you are good to go
If the column is a simple auto_incrementing integer, you could use SELECT MAX(MyAutoincrementingColumn) FROM MyTable. You might risk selecting a row that has been inserted by another user in the meantime, if your users are not using transactions.
If you don't have access to the last INSERT line, you can make a subquery to find the last inserted id:
select max(id) from <table>